Skip to content

Using JWT Tokens

Jon P Smith edited this page Jul 29, 2022 · 3 revisions

Once you have configured the JWT Token in ASP.NET Core you then need to create the code to handle authentication and creation of the JWT Token, and possibly the JWT refresh value (see JWT Token refresh explained).

This page describes the steps you need to use a JWT Token in your application. Because you can use JTW Token on it own, or with a Token refresh, some steps have two options.

NOTE: The AuthPermissions Example2 project is a ASP.NET WebAPI using JWT Token (and AuthP's JWT Refresh Token feature). You can try this application via its Swagger front-end. All the examples in this page are from that example.

1. Configure the JWT Token in ASP.NET Core

See JWT Token configuration.

2a. Create the JWT Token (without JWT refresh feature)

If you look at Rick Strahl article you will see he has to write a load code to create a valid JWT Token to return when the user logs in. The AuthP library provides a ITokenBuilder service which builds a JWT Token for you. This service can then be used in your authentication code. You can see an example of an WebAPI authentication method using the ITokenBuilder service in the Authenticate method in Example2's AuthenticateController. The the ITokenBuilder service creates JWT Token with the UserId Claim, the AuthP's Permissions claim, and if you are using multi-tenant feature, the DataKey claim.

If you want to use the ITokenBuilder service you must set up the AuthPermissionsOptions.ConfigureAuthPJwtToken data with a new AuthPJwtConfiguration class with the same data as your used in setting up the JWT Token with ASP.NET Core. You also need to provide a the length of time before the JWT Token expires (NOTE: See JWT Refresh approach later in this page).

services.RegisterAuthPermissions<Example2Permissions>( options =>
    {
        options.MigrateAuthPermissionsDbOnStartup = true;
        options.ConfigureAuthPJwtToken = new AuthPJwtConfiguration
        {
            Issuer = jwtData.Issuer,
            Audience = jwtData.Audience,
            SigningKey = jwtData.SigningKey,
            TokenExpires = new TimeSpan(2, 0, 0, 0), //The JWT Token will last for 2 days
        };
    })
    //... other AuthP configurations left out

NOTE: If you want to create your own JWT Token then you can. In this case you don't have set the AuthPermissionsOptions.ConfigureAuthPJwtToken, but for AuthP to work you need to include the AuthP claims. You can get these via AuthP's IClaimsCalculator service.

2b - Creating the JWT Token WITH JWT refresh feature

In the JWT Token refresh explained I cover why using a JWT refresh approach improved the security of using JWT Tokens. To use AuthP's JWT refresh feature you have to Alter ConfigureAuthPJwtToken configuration data. This because when using the JWT refresh feature you want the:

  • JWT Token to expires quickly - say minutes rather than days
  • You need to define how long the JWT refresh value is still valid

In AuthP configuration shown below shows this

services.RegisterAuthPermissions<Example2Permissions>( options =>
    {
        options.MigrateAuthPermissionsDbOnStartup = true;
        options.ConfigureAuthPJwtToken = new AuthPJwtConfiguration
        {
            Issuer = jwtData.Issuer,
            Audience = jwtData.Audience,
            SigningKey = jwtData.SigningKey,
            TokenExpires = new TimeSpan(0, 5, 0), //The JWT Token will last for 5 minutes
            RefreshTokenExpires = new TimeSpan(1,0,0,0) //Refresh token is valid for one day
        };
    })
    //... other AuthP configurations left out

NOTE: Look at the ASP.NET Core JWT Token setup part Example2 Startup class and you will see there is useful event that Rui Figueiredo suggests. You might find that useful.

3a. Just JWT Token - Create a WebAPI for login

You need to create a WebAPI for login that will return the JWT Token. This will:

  1. Authenticate the user that is logging in - the actual authentication code relies on your authentication provider.
  2. If authenticated OK, then return a JWT Token.

The Authenticate method in Example2's AuthenticateController provides you with and example of how this is done.

3b. JWT Token with refresh

This requires two WebAPIs and some front-end code

  • Create a WebAPI for login
  • Create a WebAPI for refresh
  • Front-end code to execute a refresh.

3b-1. Create a WebAPI for login

When using AuthP's Token refresh feature the authentication is the same, but the WebAPI returns the JWT Token and the JWT Refresh value. You can see this in the AuthenticateWithRefresh method in Example2's AuthenticateController.

3b-2. Add a WebAPI JWT Refresh method

When front-end code detects that the JWT Token it needs to go to a different authentication method to refresh (see the diagram in JWT Token refresh explained). This takes in the old JWT Token and the JWT Refresh value and, if they are valid, it will sent back a new JTW Token and the new JWT Refresh value.

You can see the RefreshAuthentication method in Example2's AuthenticateController.

3b-3. Front-end code to execute a refresh.

I'm not an expert on front-end code so I can't speak to this, but a google of "jwt token refresh angular", "jwt token refresh react" and so on returns some useful articles. Call this a) when a user logs out, or b) you want to log out an active user when the JTW times out.

Revoking a user's refresh Token

There is a service with the interface IDisableJwtRefreshToken which allows you to revoke a refresh Token.

EXTRA: Sending the current user's Permissions to the front-end

Your front-end code most likely want to only show links that the current user can access, which means your front-end need current user's Permissions. You can create a WebAPI that returns the current user's Permissions by using the IUsersPermissionsService, which returns a list of names of the current user's permissions. See the GetUsersPermissions method in Example2's AuthenticateController.

The front-end should call this WebAPI after:

  • A login.
  • When the JWT Token is refreshed.

Articles / Videos

Concepts

Setup

Usage

Admin

SupportCode

Clone this wiki locally