简体   繁体   中英

ASP.NET Core and JSON Web Tokens - Custom claims mapping

ASP.NET Core has it's own mapping to standard claims. Read this and take a look at this GitHub repository

I am using Azure AD, NET5.

The problem is that unique_name get mapped to name and if you are real lucky you will end up with two name claims. For me one with my full name and one with my email.

Code for handling duplicated name claims.

string email = null;
var nameClaims = httpCtx.User
                        .FindAll(x => x.Type.Equals(ClaimTypes.Name))
                        .Where(x => x.Value.Contains("@")).ToList();
if(nameClaims.Any())
{
  email = nameClaims.First().Value;
}     

Code for adding auth.

services  
 .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
 .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
 options.Authority = openIdConnectOptions.Authority;
 options.TokenValidationParameters.ValidIssuer = openIdConnectOptions.ValidIssuer;
 options.TokenValidationParameters.ValidAudiences = openIdConnectOptions.ValidAudiences;
 options.MapInboundClaims = true;
});

If you set MapInboundClaims = false then there will be now mappings and all claims will keep there names. This solves my problem with duplicated name claim but also break how roles are mapped an used in ASP.NET Core.

I would like to keep the default mapping and add my own for the types I know get wrongly mapped. Or remove all mappings and add the missing parts to make roles work again.

This is what I ended up with. Now claim names are not changes. Except for roles. I needed to add MS claim names to get roles to work in my policy mapping.

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Logging;

namespace EmployeeTrading.Server.Extensions
{
    public static partial class ServiceCollectionExtensions
    {
        public static IServiceCollection AddBearerAuthentication(this IServiceCollection services,
            OpenIdConnectOptions openIdConnectOptions)
        {
#if DEBUG
            IdentityModelEventSource.ShowPII = true;
#endif
            // // https://mderriey.com/2019/06/23/where-are-my-jwt-claims/
            // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/a301921ff5904b2fe084c38e41c969f4b2166bcb/src/System.IdentityModel.Tokens.Jwt/ClaimTypeMapping.cs

            services
                .AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", o =>
                {
                    o.Authority = openIdConnectOptions.Authority;
                    o.TokenValidationParameters.ValidIssuer = openIdConnectOptions.ValidIssuer;
                    o.TokenValidationParameters.ValidAudiences = openIdConnectOptions.ValidAudiences;
                    o.MapInboundClaims = false;
                    o.TokenValidationParameters.RoleClaimType = "roles";
                });

            return services;
        }
    }
}

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