All Projects → Xabaril → Jwtsimpleserver

Xabaril / Jwtsimpleserver

Licence: apache-2.0
A lightweight, dynamic jwt server for ASP.NET Core

Projects that are alternatives of or similar to Jwtsimpleserver

SignalR-Core-SqlTableDependency
Shows how the new SignalR Core works with hubs and sockets, also how it can integrate with SqlTableDependency API.
Stars: ✭ 36 (-80.11%)
Mutual labels:  asp-net-core, netcore2
SQLiteEncryptionUsingEFCore
SQLite Encryption using Entity Framework Core (EFCore)
Stars: ✭ 42 (-76.8%)
Mutual labels:  asp-net-core, netcore2
jQuery-datatable-server-side-net-core
A simple Visual Studio solution using jQuery DataTable with Server-Side processing using .NET 5
Stars: ✭ 71 (-60.77%)
Mutual labels:  asp-net-core, netcore2
Jwtsecurity
JWT Server for Asp.Net Core and Asp.Net WebAPI2
Stars: ✭ 16 (-91.16%)
Mutual labels:  asp-net-core, netcore2
Security.identity
.NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities
Stars: ✭ 165 (-8.84%)
Mutual labels:  asp-net-core
52abp.school
52ABP实战系列教程入门-52ABP学校管理系统
Stars: ✭ 152 (-16.02%)
Mutual labels:  asp-net-core
Westwind.aspnetcore.markdown
An ASP.NET Core Markdown support library that provides Markdown parsing, a Markdown TagHelper and Markdown Page Handler Middleware
Stars: ✭ 148 (-18.23%)
Mutual labels:  asp-net-core
Blazorise
Blazorise is a component library built on top of Blazor with support for CSS frameworks like Bootstrap, Bulma, AntDesign, and Material.
Stars: ✭ 2,103 (+1061.88%)
Mutual labels:  asp-net-core
Dynamicrolebasedauthorizationnetcore
Dynamic Role-Based Authorization in ASP.NET Core MVC 2.1, 3.1 and 5.0
Stars: ✭ 174 (-3.87%)
Mutual labels:  asp-net-core
Netcore Boilerplate
Boilerplate of API in .NET Core 3.1
Stars: ✭ 166 (-8.29%)
Mutual labels:  asp-net-core
Active Directory B2c Dotnetcore Webapp
An ASP.NET Core web application that can sign in a user using Azure AD B2C, get an access token using MSAL.NET and call an API.
Stars: ✭ 160 (-11.6%)
Mutual labels:  asp-net-core
Aspnetcore
ASP.NET Core Extension Library
Stars: ✭ 152 (-16.02%)
Mutual labels:  asp-net-core
Identitymanager2
Development tool for administering users and roles
Stars: ✭ 164 (-9.39%)
Mutual labels:  asp-net-core
Rapidcms
RapidCMS is a Blazor framework which allows you to build a responsive and flexible CMS purely from code. It provides a basic set of editors and controls, and is fully customisable.
Stars: ✭ 149 (-17.68%)
Mutual labels:  asp-net-core
Lyniconanc
Lynicon CMS for ASP.Net Core for .Net Standard 2.0/2.1 and .Net 4.6.1/4.6
Stars: ✭ 173 (-4.42%)
Mutual labels:  asp-net-core
Vuejsssrsample
ASP.NET Core Vue.js server-side rendering sample:
Stars: ✭ 146 (-19.34%)
Mutual labels:  asp-net-core
Bitframework
Full stack dev framework for C# / TypeScript / JavaScript developers
Stars: ✭ 158 (-12.71%)
Mutual labels:  asp-net-core
Netcorecms
NetCoreCMS is a modular theme supported Content Management System developed using ASP.Net Core 2.0 MVC. Which is also usable as web application framework. This project is still under development. Please do not use before it's first release.
Stars: ✭ 165 (-8.84%)
Mutual labels:  asp-net-core
Firewall
ASP.NET Core middleware for IP address filtering.
Stars: ✭ 159 (-12.15%)
Mutual labels:  asp-net-core
Abot
Cross Platform C# web crawler framework built for speed and flexibility. Please star this project! +1.
Stars: ✭ 1,961 (+983.43%)
Mutual labels:  netcore2

Build status MyGet CI NuGet npm version

Build history

JWT Simple Server

A light-weight, dynamic jwt server for ASP.NET Core 2.1

What is the motivation behind it?

JWT Simple server arises from the need of having an ease-to-use JWT server in ASP.NET, avoiding the user all the ceremony configuration and providing additional features.

What JWT Simple Server offers?

  • Easy to use JWT Server, configured with a few lines of code.
  • Flexible and customizable. You can provide your own authentication and store mechanisms.
  • Implements middleware that exposes the token endpoint so you don't have to create and mantain your own.
  • Provides refresh tokens feature with several store implementations (InMemory, Entity Framework, Redis, Message Pack).
  • Provides a typescript library that will allow you to interact with JWT Server easily. This library offers a JWT Client to request and refresh access tokens and a refresh token automatic renewal service.

Getting Started

  1. Install the standard Nuget package into your ASP.NET Core application.

    Install-Package JWTSimpleServer
    
    Install-Package JWTSimpleServer.InMemoryRefreshTokenStore
    
  2. Create your own IAuthenticationProvider for user authentication. You should execute context.success and provide the user claims that will be encoded in the token or context.Reject if the authentication was not successful.

    public class CustomAuthenticationProvider : IAuthenticationProvider
    {
        public Task ValidateClientAuthentication(JwtSimpleServerContext context)
        {
            if(context.UserName == "demo" && context.Password == "demo")
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Name, "demo"));
    
                context.Success(claims);
            }
            else
            {
                context.Reject("Invalid user authentication");
            }
    
            return Task.CompletedTask;
        }
    }
    
  3. In the ConfigureServices method of Startup.cs, register JWTSimpleServer services, defining one refresh token store (Optional: By default we register NoRefreshTokenStore implementation).

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddSingleton<IAuthenticationProvider, CustomAuthenticationProvider>()
            .AddJwtSimpleServer(setup =>
            {
                setup.IssuerSigningKey = SigningKey;
            })
            .AddJwtInMemoryRefreshTokenStore();
    }
    
  4. In the Configure method, add the middleware to the server exposing the token endpoint and handling it's requests.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
          app.UseJwtSimpleServer(setup =>
          {
              setup.IssuerSigningKey = SigningKey;
          });
    }
    
  5. Two grant types are supported right now by the server: password and refresh_token

    	A **_password_** grant type request will require username and password parameters and will allow you to obtain an **_access token_**.
    
    	Sample request:
    	```html
    	POST https://localhost:44305/Token HTTP/1.1
    	Host: localhost:44305
    	User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
    	Accept: */*
    	Content-Type: application/x-www-form-urlencoded; charset=UTF-8
    	X-Requested-With: XMLHttpRequest
    	Referer: https://localhost:44305/
    	Content-Length: 68
    
    	grant_type=password&username=demo&password=demo
    	```
    	HTTP Response
    
    	```json
    	{
    		"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9....",
    		"expires_in": 900,
    		"refresh_token": "77e248a4a3814308931d63b10fb1e7f7"
    	}
    	```
    

    A refresh_token grant type will allow you to generate a new access token with a new expiry time and obtain a new refresh token. (The previous refresh token will be invalidated once used).

    The required parameter for this grant type is the refresh token you were previously provided.

    	Sample request:
    	```html
    	POST https://localhost:44305/Token HTTP/1.1
    	Host: localhost:44305
    	User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
    	Accept: */*
    	Content-Type: application/x-www-form-urlencoded; charset=UTF-8
    	X-Requested-With: XMLHttpRequest
    	Referer: https://localhost:44305/
    	Content-Length: 68
    
    	grant_type:refresh_token&refresh_token:77e248a4a3814308931d63b10fb1e7f7
    	```
    
    	HTTP Response
    
    	```json
    	{
    		"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9....",
    		"expires_in": 900,
    		"refresh_token": "3521442655fc4ec5b41a1b2d9ce846aa"
    	}
    	```
    

Available stores

JWT Simple Server has four different store implementations:

  • In-memory store
   public void ConfigureServices(IServiceCollection services)
   {
       services
           .AddSingleton<IAuthenticationProvider, CustomAuthenticationProvider>()
           .AddJwtSimpleServer(setup =>
           {
               setup.IssuerSigningKey = SigningKey;
           })
           .AddJwtInMemoryRefreshTokenStore();
   }
  • Entity framework store
    public void ConfigureServices(IServiceCollection services)
       {
           services
               .AddScoped<IAuthenticationProvider, CustomAuthenticationProvider>()
               .AddJwtSimpleServer(options => options.IssuerSigningKey = SigningKey)
               .AddJwtEntityFrameworkCoreRefreshTokenStore(options =>
               {
                   options.ConfigureDbContext = builder =>
                   {
                       builder.UseSqlServer(
                           Configuration["ConnectionStrings:DefaultConnection"],
                           sqlServerOptions => sqlServerOptions.MigrationsAssembly(typeof(Startup).Assembly.FullName));
                   };
               });
       }
  • Redis store
public void ConfigureServices(IServiceCollection services)
      {
          services.AddSingleton<IAuthenticationProvider, CustomAuthenticationProvider>()
          .AddJwtSimpleServer(setup =>
          {
              setup.IssuerSigningKey = SigningKey;
          })
          .AddDistributedRedisRefreshStokenStore( setup =>
          {
            setup.Configuration = "localhost"; //Provide your redis server configuration
            setup.InstanceName = "JwtSimpleServerInstance";
          });
      }
  • Message pack binary store
public void ConfigureServices(IServiceCollection services)
      {
          services.AddSingleton<IAuthenticationProvider, CustomAuthenticationProvider>()
          .AddJwtSimpleServer(setup =>
          {
              setup.IssuerSigningKey = SigningKey;
          })
          .AddJwtMessagePackRefreshTokenStore(setup =>
          {
              setup.Path = "MyBinaryStore.bin";
          });
      }

You can create your own store service by implementing IRefreshTokenStore interface and registering it in the inversion of control container.

Pipeline configuration

If you need to register middlewares in the JwtSimpleServer branch, you can use configurePipeline action parameter in UseJwtSimpleServer extension method:

Sample to register CORS middleware within the pipeline:

app.UseJwtSimpleServer(setup =>
 {
   setup.IssuerSigningKey = SigningKey;
 }, pipeline => {
   pipeline.UseCors(setup =>
  {
    setup.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
  });
});

Samples

We have some samples with different store configurations available here.

If you launch the projects you can try a simple playground to get access tokens and try the refresh token renewal service.

JWTSimpleServer playground

Typescript library

The typescript library will allow you to easily interact will the token endpoint.

Follow this steps to create your client if you are using the browser bundled library:

NPM - Installing the library

npm install jwt-simpleserver-client --save

1. Create the client options

var defaultServerOptions = new JwtSimpleServer.ClientOptions();

Client options parameters have default values listed in this table:

Parameter default value
tokenEndpoint "/token"
host window.location.origin
httpClient XMLHttpRequestClient

NOTE: You can implement your own HttpClient by implementing our HttpClient abstract class

2. Creat the client providing the options object:

var simpleServerClient = new JwtSimpleServer.ServerClient(defaultServerOptions);
  1. Request an access token by executing requestAccessToken method:
simpleServerClient.requestAccessToken({ userName: "demo", password: "demo" })
	.then(token => {
  // your token object will have the access token and expiral, and if configured: the refresh token
   }):

*Client events

JWT client have several observables you can subscribe to:

Observable return value description
onBeforeRequestAccessToken void Will notify observers before starting the token request to the server
onRequestAccessTokenSuccess Token Will notify observers passing the retrieved token as parameter
onBeforeRequestRefreshToken void Will notify observers before starting the refresh token request to the server
onRequestRefreshTokenSuccess Token Will notify observers passing the retrieved refresh token as parameter

**4. Optional: If you want the library to request new access tokens given an interval you can configure the **RefreshTokenService****

var refreshService = new JwtSimpleServer.RefreshTokenService(
  simpleServerClient
);

let onTokenRefreshedFunction = token => {
  console.log("Refresh token service:", token);
};

//Start the renewal service
refreshService.start({
  intervalSeconds: 10,
  refreshToken,
  onRefreshTokenSuccessCallback: onTokenRefreshedFunction
});

//Stop the renewal service
refreshService.stop();
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].