Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Security and hardening

JwtBearer code stops working after moving an ASP.NET Core API to .NET 8

Errorcontext.SecurityToken as JwtSecurityToken returns null in OnTokenValidated

Short answer

Since ASP.NET Core 8, JwtBearer events return a JsonWebToken instead of a JwtSecurityToken. A cast to JwtSecurityToken now gives null. Cast to JsonWebToken instead, or set UseSecurityTokenValidators to true on JwtBearerOptions to keep the old token type. Check claim type mapping too.

  • Applies to ASP.NET Core 8, 9 and 10, Microsoft.AspNetCore.Authentication.JwtBearer
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print the runtime type of the token inside OnTokenValidated. It tells you which cause applies.

    options.Events = new JwtBearerEvents
    {
        OnTokenValidated = ctx =>
        {
            Console.WriteLine(ctx.SecurityToken.GetType().FullName);
            return Task.CompletedTask;
        }
    };
  2. 2Match what you see, then jump to its fix

    1. 1The type printed is Microsoft.IdentityModel.JsonWebTokens.JsonWebToken and the cast gives nullCode casts the token to JwtSecurityToken, which is no longer the defaultFix
    2. 2Many places depend on JwtSecurityToken and cannot change yetYou want the old token handlers until the code is migratedFix
    3. 3User.FindFirst with a long claim type name returns null after the upgradeInbound claim type mapping comes from a different tableFix

What does the error look like?

  • context.SecurityToken as JwtSecurityToken returns null in OnTokenValidated
  • Claims read by name no longer match after upgrading to .NET 8

Cause 1 of 3

Code casts the token to JwtSecurityToken, which is no longer the default

1Check

The ASP.NET Core 8 breaking-change note says the default implementation of SecurityToken changed from JwtSecurityToken to JsonWebToken, introduced in 8.0 Preview 7.

grep -rn "as JwtSecurityToken" --include=*.cs .

2Fix

Replace the cast with JsonWebToken.

OnTokenValidated = ctx =>
{
    JsonWebToken token = ctx.SecurityToken as JsonWebToken;
    return Task.CompletedTask;
}

3Verify

The token variable is no longer null and the claims you read are present.

dotnet run

Confirmed by learn.microsoft.com

Did this fix it?

Cause 2 of 3

You want the old token handlers until the code is migrated

1Check

Setting UseSecurityTokenValidators to true makes the handler keep using the old validators and keep producing JwtSecurityToken.

grep -rn "UseSecurityTokenValidators" --include=*.cs .

2Fix

Set the option on JwtBearerOptions as a temporary bridge.

builder.Services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.UseSecurityTokenValidators = true;
});

3Verify

The type printed in the first step is System.IdentityModel.Tokens.Jwt.JwtSecurityToken again.

dotnet run

Confirmed by learn.microsoft.com

Did this fix it?

Cause 3 of 3

Inbound claim type mapping comes from a different table

1Check

The same note says the default mapping now comes from JsonWebTokenHandler.DefaultInboundClaimTypeMap, where it was JwtSecurityTokenHandler.DefaultInboundClaimTypeMap. The JWT bearer guide shows MapInboundClaims as the switch for it.

grep -rn "MapInboundClaims" --include=*.cs .

2Fix

Set MapInboundClaims explicitly and read claims by the names that really appear in the token.

.AddJwtBearer(options =>
{
    options.MapInboundClaims = false;
});

3Verify

Dump the claim types for one request and confirm the names you read exist.

Console.WriteLine(string.Join(",", User.Claims.Select(c => c.Type)));

Confirmed by learn.microsoft.com

Did this fix it?

How do I stop it coming back?

  • Read the breaking-changes list for ASP.NET Core before raising the target framework.
  • Read claims through the ClaimsPrincipal rather than down-casting the token.
  • Cover one authenticated endpoint with an integration test so a change in token type shows up in CI.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Security

A valid JWT fails to decode because its segments are base64url, not base64

Convert.FromBase64String throws FormatException on a JWT segment

A JWT is three base64url segments joined by dots, and a standard base64 decoder refuses all three differences: base64url uses - and _ instead of + and /, leaves off the = padding, and the dots are not part of any base64 alphabet.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.