All Projects → GestionSystemesTelecom → Fake Authentication Jwtbearer

GestionSystemesTelecom / Fake Authentication Jwtbearer

Licence: mit
Simple way to faked an authenticated user for integration test with ASP.Net Core framework

Projects that are alternatives of or similar to Fake Authentication Jwtbearer

Aspnetcore Developer Roadmap
Roadmap to becoming an ASP.NET Core developer in 2021
Stars: ✭ 8,248 (+29357.14%)
Mutual labels:  asp-net-core
Identity.redis
ASP.NET Identity Redis Provider
Stars: ✭ 22 (-21.43%)
Mutual labels:  asp-net-core
Awesome Microservices Netcore
💎 A collection of awesome training series, articles, videos, books, courses, sample projects, and tools for Microservices in .NET Core
Stars: ✭ 865 (+2989.29%)
Mutual labels:  asp-net-core
Jpproject.identityserver4.adminui
🔧 ASP.NET Core 3 & Angular 8 Administration Panel for 💞IdentityServer4 and ASP.NET Core Identity
Stars: ✭ 717 (+2460.71%)
Mutual labels:  asp-net-core
Aspnetcore2cookieauthentication
Cookie Authentication without ASP.NET Core Identity 3.x
Stars: ✭ 19 (-32.14%)
Mutual labels:  asp-net-core
Znetcs.aspnetcore.logging.entityframeworkcore
This is Entity Framework Core logger and logger provider. A small package to allow store logs in any data store using Entity Framework Core.
Stars: ✭ 24 (-14.29%)
Mutual labels:  asp-net-core
Electron.net
Build cross platform desktop apps with ASP.NET Core (Razor Pages, MVC, Blazor).
Stars: ✭ 6,074 (+21592.86%)
Mutual labels:  asp-net-core
Carter
Carter is framework that is a thin layer of extension methods and functionality over ASP.NET Core allowing code to be more explicit and most importantly more enjoyable.
Stars: ✭ 875 (+3025%)
Mutual labels:  asp-net-core
Angular Asp.netcorewebapi Mysql Crud Project
Angular 5 + ASP.Net Core 2.0 WebAPI + MySQL CRUD Sample
Stars: ✭ 22 (-21.43%)
Mutual labels:  asp-net-core
Allready
This repo contains the code for allReady, an open-source solution focused on increasing awareness, efficiency and impact of preparedness campaigns as they are delivered by humanitarian and disaster response organizations in local communities.
Stars: ✭ 869 (+3003.57%)
Mutual labels:  asp-net-core
Ocelot
.NET core API Gateway
Stars: ✭ 6,675 (+23739.29%)
Mutual labels:  asp-net-core
Demo.aspnetcore.mvc.cosmosdb
Sample Web API powered by ASP.NET Core MVC, Azure Cosmos DB and MediatR
Stars: ✭ 19 (-32.14%)
Mutual labels:  asp-net-core
Pieshopcore
A simple pie shopping management system using ASP.NET CORE MVC application
Stars: ✭ 25 (-10.71%)
Mutual labels:  asp-net-core
Nopcommerce
The most popular open-source eCommerce shopping cart solution based on ASP.NET Core
Stars: ✭ 6,827 (+24282.14%)
Mutual labels:  asp-net-core
Ultrix
Ultrix is a meme website for collecting memes and sharing them with friends on the website.
Stars: ✭ 13 (-53.57%)
Mutual labels:  asp-net-core
Extcore
Free, open source and cross-platform framework for creating modular and extendable web applications based on ASP.NET Core
Stars: ✭ 666 (+2278.57%)
Mutual labels:  asp-net-core
Signalrsample
Real-time Charts with ASP.NET Core SignalR and Chart.js.
Stars: ✭ 23 (-17.86%)
Mutual labels:  asp-net-core
Restfulsense
A RESTFul operations client that serializes responses and throws meaningful exceptions for >= 400 status codes.
Stars: ✭ 28 (+0%)
Mutual labels:  asp-net-core
Litecodecore
基于asp.net Core 基础权限系统
Stars: ✭ 13 (-53.57%)
Mutual labels:  asp-net-core
Csla
A home for your business logic in any .NET application.
Stars: ✭ 865 (+2989.29%)
Mutual labels:  asp-net-core

Fake Authentication Jwt Bearer for ASP.NET Core 2

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 netcoreapp3.1 --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]
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].