I upgraded my ASP.NET MVC Core 7.0 website to ASP.NET MVC Core 8.0. The site uses OpenID Connect identity provider for login.
After update, my sub claim went missing in ClaimsPrincipal.Identity.Claims collection. I would get:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
when trying to get sub claim:
string userId = User.Identity.FindFirst("sub").Value;
Upon further inspection, I noticed that sub claim is actually remapped to a different claim:
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
This happens despite having default JWT token mappings removed in startup configuration (which worked previously, in ASP.NET Core 7.0 and earlier):
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
How can I fix this issue?
.NET 8.0 has various breaking changes compared to earlier version and they are listed here Breaking changes in .NET 8.
In particular, this breaking change is affecting upgrade of the NuGet package Microsoft.AspNetCore.Authentication.OpenIdConnect from 7.0.* to 8.0.*.
One of those changes, detailed here Security token events return a JsonWebToken affects Microsoft.AspNetCore.Authentication.OpenIdConnect.TokenValidatedContext.SecurityToken, which in turn affects OpenID Connect client behavior. Reason for the breaking change was 30% improvement in performance, according to the Microsoft article.
In order to fix the issue in ASP.NET Core 8.0+ the line:
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
has to be changed into:
Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.DefaultInboundClaimTypeMap.Clear();
After this change, mapping of OpenID Connect authentication claims will behave same as in earlier .NET versions.
If you are using the AddOpenIdConnect extension from Microsoft.AspNetCore.Authentication.OpenIdConnect, you can also configure it for a specific authentication handler:
builder.Services
.AddAuthentication()
.AddOpenIdConnect(options =>
{
// your configuration
options.MapInboundClaims = false;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With