GST.Fake.Authentication.JwtBearer 6.0.0

.NET 6.0
Install-Package GST.Fake.Authentication.JwtBearer -Version 6.0.0
dotnet add package GST.Fake.Authentication.JwtBearer --version 6.0.0
<PackageReference Include="GST.Fake.Authentication.JwtBearer" Version="6.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add GST.Fake.Authentication.JwtBearer --version 6.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: GST.Fake.Authentication.JwtBearer, 6.0.0"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. 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=6.0.0

// Install GST.Fake.Authentication.JwtBearer as a Cake Tool
#tool nuget:?package=GST.Fake.Authentication.JwtBearer&version=6.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Fake Authentication Jwt Bearer for .NET 6

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

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 net6.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 Versions
.NET net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows
Compatible target framework(s)
Additional computed target framework(s)
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
6.0.0 150 6/23/2022
3.0.0 30,710 1/14/2021
2.2.0 80,792 12/11/2018
2.1.2 8,291 9/28/2018
2.1.1 4,930 6/1/2018
2.1.0 903 6/1/2018
2.0.1 2,546 10/25/2017
2.0.0 2,508 10/24/2017
1.0.4 878 9/21/2017
1.0.3 926 4/12/2017
1.0.2 843 4/12/2017
1.0.1 962 4/12/2017
1.0.0 813 3/28/2017