JwtBearer code stops working after moving an ASP.NET Core API to .NET 8
context.SecurityToken as JwtSecurityToken returns null in OnTokenValidatedShort 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.
Fix it fast
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; } };2Match what you see, then jump to its fix
- 1
The type printed is Microsoft.IdentityModel.JsonWebTokens.JsonWebToken and the cast gives nullCode casts the token to JwtSecurityToken, which is no longer the defaultFix - 2
Many places depend on JwtSecurityToken and cannot change yetYou want the old token handlers until the code is migratedFix - 3
User.FindFirst with a long claim type name returns null after the upgradeInbound claim type mapping comes from a different tableFix
- 1
What does the error look like?
context.SecurityToken as JwtSecurityToken returns null in OnTokenValidatedClaims 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 runConfirmed by learn.microsoft.com
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 runConfirmed by learn.microsoft.com
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
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
ASP.NET Core cannot create the JWT because the signing key is too short or unusable
IDX10630: The '<key type>' for signing cannot be smaller than '<bits>' bits. KeySize: '<bits>'.
The error happens while the API signs the token, not while it checks one.
3 causes, each with a fixSecurity
.NET cannot convert the string to a JwtSecurityToken
SecurityTokenMalformedException
The handler only accepts a compact JWT: three dot-separated base64url segments for a signed token.
3 causes, each with a fixSecurity
AuthenticationException: your certificate validation callback returned false
System.Security.Authentication.AuthenticationException
This message means a validation callback was installed, yours or one a library added, and it returned false.
3 causes, each with a fixSecurity
DelegateAuthenticationProvider no longer exists in the Microsoft Graph .NET SDK
The type or namespace name 'DelegateAuthenticationProvider' could not be found
Microsoft Graph .NET SDK v5 removed DelegateAuthenticationProvider.
3 causes, each with a fixSecurity
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 fixSecurity
JWT validation fails and the message only says PII is hidden
401 Unauthorized
IdentityModel hides personal data in exception text by default, so the message only says PII is hidden.
3 causes, each with a fix