AspNetCore.Security.Jwt - JWT Bearer Token Security Package

I have built a package that integrates JWT Bearer Token Security into an Asp Net Core 2.0+ application.

The package

  • Makes adding JWT Bearer Token Security to your ASP NET Core 2.0+ app a breeze!!
  • Gives you an out of the box TokenController to issue Jwt tokens.
  • Integrates the TokenContoller into your app automatically.
  • Also, Swagger UI integration!

To use the package,

You can download/clone the source code from my GitHub repository

Then add a Reference to the project (AspNetCore.Security.Jwt) in your application.

Use Default authentication (Id, Password) 

Then, you can do the below steps,

Implement IAuthentication interface in your app

Validate the Id and Password here.

See Appendix A for the IdType supported.

After this validation, the Jwt token is issued by the TokenController.

using AspNetCore.Security.Jwt;  
using System.Threading.Tasks;  

namespace XXX.API {  

    public class Authenticator: IAuthentication {  

        public async Task<bool> IsValidUser(string id, string password) {  
            //Put your id authenication here.  
            return true;  
        }  
    }  
}

The Authenticator is automatically wired up for dependency injection (Scoped).

In your Startup.cs

Add the package to your application with the below in your app’s Startup.cs.

using AspNetCore.Security.Jwt;  
using Swashbuckle.AspNetCore.Swagger;  

public void ConfigureServices(IServiceCollection services) {
    ...

    services.AddSwaggerGen(c => {  
        c.SwaggerDoc("v1", new Info {  
            Title = "XXX API", Version = "v1"  
        });  
    });  
    services.AddSecurity<Authenticator>(this.Configuration, true);  
    services.AddMvc().AddSecurity();  
}
  
public void Configure(IApplicationBuilder app, IHostingEnvironment env)   
{
   ...   
   // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),   
   // specifying the Swagger JSON endpoint.   
   app.UseSwaggerUI(c =>   
   {   
       c.SwaggerEndpoint("/swagger/v1/swagger.json", "XXX API V1");   
   });   

   app.UseSecurity(true); 
   app.UseMvc();   
}

In your appsettings.json

Add the SecuritySettings to the appsettings.json. These settings control the JWT token creation.

{  
    "SecuritySettings": {  
        "Secret": "a secret that needs to be at least 16 characters long",  
        "Issuer": "your app",  
        "Audience": "the client of your app",  
        "IdType": "Name",  
        "TokenExpiryInHours": 2  
    },  
    ...  
}

Use custom User model authentication

Create your User model

Your custom User model must inherit from IAuthenticationUser. 

using AspNetCore.Security.Jwt;  
using System;  
.  
.  
public class UserModel : IAuthenticationUser  
{  
    public string Id { get; set; }  
  
    public string Password { get; set; }  
  
    public string Role { get; set; }  
  
    public DateTime DOB { get; set; }  
}

Implement IAuthentication<TUserModel> interface in your app 

Validate your User model here.

After this validation, the Jwt token is issued by the TokenController.

using AspNetCore.Security.Jwt;  
using System.Threading.Tasks;  
  
namespace XXX.API  
{  
    public class Authenticator : IAuthentication<UserModel>  
    {          
        public async Task<bool> IsValidUser(UserModel user)  
        {  
            //Put your User model authenication here.  
            return true;  
        }  
    }  
} 

In your Startup.cs

Specify your IdTypes (ClaimTypes) from your custom User model using AddClaim.

Basically, this uses Claim under the covers. So you can verify these Claims in your Controller's action just as usual. See Appendix B.

All these ClaimTypes will be used in the token generation.

You can specify multiple Claim Types.

using AspNetCore.Security.Jwt;  
using Swashbuckle.AspNetCore.Swagger;..  
public void ConfigureServices(IServiceCollection services) {..  
    services.AddSwaggerGen(c => {  
        c.SwaggerDoc("v1", new Info {  
            Title = "XXX API", Version = "v1"  
        });  
    });  
    services.AddSecurity < Authenticator, UserModel > (this.Configuration, builder => builder.AddClaim(IdType.Name, userModel => userModel.Id).AddClaim(IdType.Role, userModel => userModel.Role).AddClaim("DOB", userModel => userModel.DOB.ToShortDateString()), true);  
    services.AddMvc().AddSecurity < UserModel > ();  
}  
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {...  
    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),     
    // specifying the Swagger JSON endpoint.    
    app.UseSwaggerUI(c => {  
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "XXX API V1");  
    });  
    app.UseSecurity(true);  
    app.UseMvc();  
}

In your appsettings.json

{  
  "SecuritySettings": {  
    "Secret": "a secret that needs to be at least 16 characters long",  
    "Issuer": "your app",  
    "Audience": "the client of your app",  
    "TokenExpiryInHours" :  2  
  },  
  .  
  .  
  .  
}

In your Controller that you want to secure

You must mark the Controller or Action that you want to secure with Authorize attribute like,

using Microsoft.AspNetCore.Mvc;
...

namespace XXX.API.Controllers {  
    using Microsoft.AspNetCore.Authorization;
  
    [Authorize]
    [Route("api/[controller]")] 
    public class XXXController: Controller {
      ...  
    }  
} 

TokenController - Issues the JWT token

The TokenContoller has a POST Method which you can call with a Id and Password.

The Id has to match the specified IdType.

The POST in Postman is like below,

 JWT Bearer Token Security Package

A Jwt Bearer token is then issued which must be sent in subsequent requests in the header.

Access your secure Controller or Action

You have to send the issued Jwt token in the header of the request as

Authorization: Bearer <token>

Eg.

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1
LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiU2hhbiIsImV4cCI6MTU0MjUxMTkzOSwibmJmIjoxNTQwMDkyNzM5LCJpc3MiOiJ5
b3VyIGFwcCIsImF1ZCI6InRoZSBjbGllbnQgb2YgeW91ciBhcHAifQ.VktS3XGD-Z3-wNuXl4IuLLJXe9OUNK5RZ8o-9eUUVuE

to access the Controller or Action.

This is like below in Postman,

JWT Bearer Token Security Package 

In the Angular 2+ app, you can do this using HttpInterceptors.

Swagger UI integration

When you start Swagger you will see a Token endpoint automatically.

Also, you will see an Authorize button.

JWT Bearer Token Security Package 

You obtain the Jwt token by entering your Id and Password on the Token Endpoint.

Then you enter the token into the Value field after clicking on the Authorize button as,

AspNetCore.Security.Jwt - JWT Bearer Token Security Package

Then, you can make calls to all secured endpoints (marked with Authorize attribute).

Appendix A

IdType is an enum.

All ClaimTypes are available via this enum.

The IdType your app will use is specified in the SecuritySettings of your appsettings.json.

That can be any one of the ones specified in the enum below,

public enum IdType  
{  
    Actor,  
    PostalCode,  
    PrimaryGroupSid,  
    PrimarySid,  
    Role,  
    Rsa,  
    SerialNumber,  
    Sid,  
    Spn,  
    StateOrProvince,  
    StreetAddress,  
    Surname,  
    System,  
    Thumbprint,  
    Upn,  
    Uri,  
    UserData,  
    Version,  
    Webpage,  
    WindowsAccountName,  
    WindowsDeviceClaim,  
    WindowsDeviceGroup,  
    WindowsFqbnVersion,  
    WindowsSubAuthority,  
    OtherPhone,  
    NameIdentifier,  
    Name,  
    MobilePhone,  
    Anonymous,  
    Authentication,  
    AuthenticationInstant,  
    AuthenticationMethod,  
    AuthorizationDecision,  
    CookiePath,  
    Country,  
    DateOfBirth,  
    DenyOnlyPrimaryGroupSid,  
    DenyOnlyPrimarySid,  
    DenyOnlySid,  
    WindowsUserClaim,  
    DenyOnlyWindowsDeviceGroup,  
    Dsa,  
    Email,  
    Expiration,  
    Expired,  
    Gender,  
    GivenName,  
    GroupSid,  
    Hash,  
    HomePhone,  
    IsPersistent,  
    Locality,  
    Dns,  
    X500DistinguishedName  
}

Appendix B

Verify Claims in your Controller action.

This is done as usual. To map between IdType to ClaimTypes use ToClaimTypes() extension.

using AspNetCore.Security.Jwt;  
using Microsoft.AspNetCore.Authorization;  
using Microsoft.AspNetCore.Mvc;  
.  
.  
[HttpGet("cheapest/{title}")]  
public async Task<IEnumerable<ProviderMovie>> GetCheapestDeal(string title)  
{  
    var currentUser = HttpContext.User;  
  
    //Verify Claim  
    if (currentUser.HasClaim(x => x.Type == "DOB") && currentUser.HasClaim(x => x.Type == IdType.Role.ToClaimTypes()))  
    {  
        //Do something here  
    }  
  
    return await _moviesRepository.GetCheapestDeal(title);  
}

Notes

The Package integrates JWT bearer token security into your app quickly.

But, you can modify the source code to suit the kind of Token you want to generate.

You can do this in the GenerateToken method of the SecurityService (in the SecurityService.cs code file).