Iris Classon
Iris Classon - In Love with Code

ASPNET Core OpenIdConnect: Why is the ClaimsPrincipal name NULL?

I’m setting up OpenIdConnect authentication for our system and came across a peculiar problem. Although I was able to log in using an external authentication server (for example a Google account) the HttpContext.User.Identity.Name would be null. But looking at the claims I could see a name claim. What was going on?

When you authenticate the ClaimsPrincipal is set, and by default the name claim type used is http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name , however if you look at the claims received the user name claim is “name”. To override this default behavior and set the User.Identity.Name make sure to set the TokenValidationParameter NameClaimType to “name”.

 
.AddOpenIdConnect(options =>
{
   options.ClientId = Configuration["ClientId"];
   options.ClientSecret = Configuration["ClientSecret"];
   options.Authority = Configuration["Authority"];
 
   options.ResponseType = OpenIdConnectResponseType.Code;
 
   options.TokenValidationParameters = new TokenValidationParameters
   {
       NameClaimType = "name",
       ValidateIssuer = true
   };
 
   options.SaveTokens = true;
});

Comments

Leave a comment below, or by email.


Last modified on 2018-09-18

comments powered by Disqus