简体   繁体   中英

How to read custom claim value from JWT security token in .NET Core 6.0

I can't read token claims from Bearer JWT token.

Login is working, the HTTP request comes with a valid JWT token to the backend. Login returns the token. Here is my code on server side:

Program.cs

builder.Services.AddAuthentication(m => {
    //m.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    m.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    m.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(conf => {
        conf.RequireHttpsMetadata = false;
    conf.SaveToken = true;
    conf.TokenValidationParameters = new TokenValidationParameters
   {
       ValidateIssuer = true,
       ValidateAudience = true,
       ValidIssuer = Configuration["JWT-Issuer"],
       ValidAudience = Configuration["JWT-Issuer"],
       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT-Key"])),
       ClockSkew = TimeSpan.Zero,
};
});

When I uncomment this line //m.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; postman says unauthorized. When it is kept commented, authorization succeeds.

Token is generated here.

GenerateToken Method:

private object GenerateJwtToken(string Id, string email, ApplicationUser appUser, string appUserRole, string FirstName)
        {
            List<Claim> claims = null;
            claims = new List<Claim> {
                new Claim(JwtRegisteredClaimNames.Email,email),
                new Claim(JwtRegisteredClaimNames.Jti, appUser.Id),
                new Claim("Role",appUserRole),
                new Claim("UserName",appUser.UserName),
                new Claim("TEMP", FirstName)
                }
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT-Key"]));
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expire = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JWT-Expiry"]));


            var token = new JwtSecurityToken(
                issuer: _configuration["JWT-Issuer"],
                audience: _configuration["JWT-Issuer"],
                claims: claims,
                expires: expire,
                signingCredentials: cred
                );


            return new JwtSecurityTokenHandler().WriteToken(token);

        }

When JWT Bearer token is passed to the API call decorated with [Authorize] and tested with debugger it shows that custom claim like TEMP is not present in the User.Claims List.

Reading Claims From Token

  string Email = User.Claims.SingleOrDefault(x => x.Type.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")).Value;
  string FirstName= User.Claims.SingleOrDefault(x => x.Type.Equals("TEMP")).Value;

Here, the email can be read successfully but I can't read the FirstName from the token. In fact User.Claims doesn't have the FirstName claim (I mean all the custom claims leaving the Registered JWT Default ClaimTypes), it only has the default token parameters which are emailaddress, id, role etc.

What should I do? should I need to create custom authentication scheme for this purpose?

Internally in AddJwtBearer, there are some remapping done by the Token hander, where claims are renamed, like

email -> http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress

This mapping can be turned of using:

// Or set this flag to false
.AddJwtBearer(opt =>
{
    ...
    opt.MapInboundClaims = false;
});

or setting:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

The actual mapping can be found here

However, I am not sure why the TEMP claim is not found. What claims do you actually see in the authenticated User in your controller? Some claims in some cases are also ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM