skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    .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.


  2. Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.DefaultInboundClaimTypeMap.Clear();

    If you apply this solution, it will clear all policies. You can specifically specify the claim you want to clear. Example:

    JsonWebTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search