JwtSecurityToken in .NET 8 – Jwt

by
Ali Hasan
.net-8.0 jwt

Quick Fix: In ASP.NET Core 8, the TokenValidatedContext.SecurityToken property returns a JsonWebToken object instead of a JwtSecurityToken. Update your code to check for the new type and remove references to the System.IdentityModel.Tokens.Jwt.dll library.

The Problem:

In .NET 8, the code used for checking the validity of a JWT token in a database is causing errors. The code involves inspecting the SecurityToken property of the AuthorizationHandlerContext object and checking the presence of a RawData property on the returned JwtSecurityToken. Additionally, the code attempts to validate the token’s RawData against a token store service. However, this code is no longer working after upgrading from .NET 7 to .NET 8.

The Solutions:

Solution 1: Change of ‘SecurityToken’s Returned Type’

In previous versions of ASP.NET Core (below version 8), `TokenValidatedContext.SecurityToken` property returned a `JwtSecurityToken` object. However, in ASP.NET Core 8, it returns a newer `JsonWebToken` object. The difference is in the library they come from: `JwtSecurityToken` comes from `System.IdentityModel.Tokens.Jwt` library whereas `JsonWebToken` is part of `Microsoft.IdentityModel.JsonWebTokens` library.

To make your code compatible with ASP.NET Core 8, simply replace `JwtSecurityToken` checks with `JsonWebToken` checks. Also, `JwtSecurityToken.RawData` property is not present in `JsonWebToken`. If you need the raw JWT string, you can use the `UnsafeToString` method of `JsonWebToken`.

Here’s an example of the code that checks if a token exists in a database:

using Microsoft.IdentityModel.JsonWebTokens;

TokenValidatedContext ctx = ...
if (ctx.SecurityToken is JsonWebToken jwt)
{
    String rawJwt = jwt.UnsafeToString();
    Boolean isValid = await tokenStoreService.IsValidTokenAsync(rawJwt, userId, cancellationToken).ConfigureAwait(false);
    if (!isValid)
    {
        context.Fail("This token is not in our database.");
        return;
    }
}

Q&A

How to use JwtSecurityToken in .NET 8?

It is now replaced with JsonWebToken. Change your code to test for the new type instead.

How to check if a token exists in the database in .NET 8?

Use UnsafeToString() method of JsonWebToken to convert it to a string and then check the database.

Is it necessary to check if a token exists in the database?

No, it is not necessary if you have a well-designed application with proper JWT usage.

Video Explanation:

The following video, titled "Token Authentication In ASP.NET Core 7 With JWT | Clean ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... Login API endpoint to get JWT 8:17 Generating the JWT 15:30 Configuring Authentication in ASP.NET Core 21:28 Inspecting the generated JWT.