GST.Fake.Authentication.JwtBearer 7.0.2

dotnet add package GST.Fake.Authentication.JwtBearer --version 7.0.2                
NuGet\Install-Package GST.Fake.Authentication.JwtBearer -Version 7.0.2                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GST.Fake.Authentication.JwtBearer" Version="7.0.2" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add GST.Fake.Authentication.JwtBearer --version 7.0.2                
#r "nuget: GST.Fake.Authentication.JwtBearer, 7.0.2"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install GST.Fake.Authentication.JwtBearer as a Cake Addin
#addin nuget:?package=GST.Fake.Authentication.JwtBearer&version=7.0.2

// Install GST.Fake.Authentication.JwtBearer as a Cake Tool
#tool nuget:?package=GST.Fake.Authentication.JwtBearer&version=7.0.2                

Fake Authentication Jwt Bearer for .NET 7

Build status

This code allow to fake a Jwt Bearer and build integration test for ASP.Net Core application.
By this way we can fake any authentication we need, without the need to really authenticate a user.
This code is based on Microsoft.AspNetCore.Authentication.JwtBearer.

If You need it for ASP.NET Core 1, check Tag 1.0.4

If You need it for ASP.NET Core 2.1, check Tag 2.1.2

If You need it for ASP.NET Core 3.1, check Tag 3.0.0

If You need it for ASP.NET Core 6.0, check Tag 6.0.0

How to install it?

First add this package to your Nuget configuration file : GST.Fake.Authentication.JwtBearer.

Let's imagine we are coding integration tests in the project MyApp.TestsIntegration.

This is the tree of the global solution:

+--src
| +---MyApp
| +---SecondApp
+---test
| +---MyApp.Tests
| +---MyApp.TestsIntegration

My integration test are based on this tutorial Introduction to integration testing with xUnit and TestServer in ASP.NET Core.
So I have a TestFixture.cs file where I can extend configurations made in the Startup.cs file.

In the class TestFixture.cs we have to extend the configuration of our Startup.
You have to disable you original AddJwtBearer in your Startup.cs, because the AddFakeJwtBearer doesno't overload the original.

public class TestFixture<TStartup> : IDisposable where TStartup : class
{
    public TestFixture()
    {
    // ...

    // We must configure the realpath of the targeted project
    string appRootPath = Path.GetFullPath(Path.Combine(
                    PlatformServices.Default.Application.ApplicationBasePath
                    , "..", "..", "..", "..", "..", "..", "src", baseNamespace));

    var builder = new WebHostBuilder()
      .UseContentRoot(appRootPath)
      .UseStartup<TStartup>()
      .UseEnvironment("Test")
      .ConfigureServices(x =>
      {
          // Here we add our new configuration
          x.AddAuthentication(options =>
           {
                options.DefaultScheme = FakeJwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = FakeJwtBearerDefaults.AuthenticationScheme;
           	options.DefaultChallengeScheme = FakeJwtBearerDefaults.AuthenticationScheme;
           }).AddFakeJwtBearer();
      });
      // ...
    }
}

How to use it?

Now all the things are tied up, how to faked a user?

I've defined tree methods :

  • A token with a custom object
  • A token with a Username
  • A token with a Username and some roles

Let see that in a real world example.

 using GST.Fake.Authentication.JwtBearer;
 using Newtonsoft.Json;
 using Newtonsoft.Json.Linq;
 using System;
 using System.Collections.Generic;
 using System.Net.Http;
 using System.Text;
 using Xunit;

 namespace MyApp.TestsIntegration
 {
     public class SomeWeirdTest : IClassFixture<TestFixture<MyApp.Startup>>
     {
         private TestFixture<MyApp.Startup> fixture;

         public SomeWeirdTest(TestFixtureMyApp.Startup> _fixture)
         {
             fixture = _fixture;
             // Create a token with a Username and two roles
             fixture.Client.SetFakeBearerToken("admin", new[] { "ROLE_ADMIN", "ROLE_GENTLEMAN" });
         }

         [Fact]
         public void testCallPrivateAPI()
         {
             // We call a private API with a full authenticated user (admin)
             var response = fixture.Client.GetAsync("/api/my-account").Result;
             Assert.True(response.IsSuccessStatusCode);
         }

		 
         [Fact]
         public void testCallPrivate2API()
         {
		 dynamic data = new System.Dynamic.ExpandoObject();
            data.organism = "ACME";
            data.thing = "more things";
            fixture.Client.SetFakeBearerToken("SUperUserName", new[] { "Role1", "Role2" }, (object)data);

            // We call a private API with a full authenticated user (admin)
            var response = fixture.Client.GetAsync("/api/my-account").Result;
            Assert.True(response.IsSuccessStatusCode);
         }
     }
 }

Create Nuget Package

dotnet build src/GST.Fake.Authentication.JwtBearer/GST.Fake.Authentication.JwtBearer.csproj --configuration Release --framework net7.0 --force
dotnet pack src/GST.Fake.Authentication.JwtBearer/GST.Fake.Authentication.JwtBearer.csproj --configuration Release --include-source --include-symbols --output ../../nupkgs
dotnet nuget push src/GST.Fake.Authentication.JwtBearer/bin/Release/GST.Fake.Authentication.JwtBearer.[VERSION].nupkg -s https://api.nuget.org/v3/index.json -k [API-KEY]
Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
7.0.2 21,546 10/17/2023
7.0.0 38,752 12/6/2022
6.0.0 54,705 6/23/2022
3.0.0 75,835 1/14/2021
2.2.0 115,001 12/11/2018
2.1.2 10,311 9/28/2018
2.1.1 5,517 6/1/2018
2.1.0 1,607 6/1/2018
2.0.1 2,977 10/25/2017
2.0.0 2,763 10/24/2017
1.0.4 1,149 9/21/2017
1.0.3 1,173 4/12/2017
1.0.2 1,077 4/12/2017
1.0.1 1,190 4/12/2017
1.0.0 1,081 3/28/2017