在 OAuthBearer 中间件上使用自定义 RoleClaimType

Using custom RoleClaimType on OAuthBearer middleware

OAuth 服务器使用来自 System.Security.Claims.ClaimTypes.Role 的不同声明类型发布角色声明:

var adminRole = new Claim("CustomRole", "Admin");
context.Ticket.Identity.AddClaim(adminRole);

我如何告诉 OAuthBearerAuthentication 中间件使用我的自定义角色声明类型,以便它使 Authorize 属性起作用:

//Startup
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions ...

[Authorize(Roles = "Admin")]
public IHttpActionResult SecureAction()

确保您的 Identity 设置为 System.Security.Claims.ClaimsIdentity 的实例:

您可以轻松地从原始身份克隆原始身份(传递原始声明)并使用构造函数指定不同的 roleType 名称:

ClaimsIdentity(IIdentity, IEnumerable<Claim>, String, String, String)

OAuthBearerAuthenticationProvider, we can rebindClaimsIdentitywith appropriateRolaClaimTypeandNameClaimType` 的 OnValidateIdentity 函数中:

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
    Provider = new OAuthBearerAuthenticationProvider
    {
        OnValidateIdentity = context =>
        {
            var claimsIdentity = new ClaimsIdentity(
                context.Ticket.Identity.Claims,
                OAuthDefaults.AuthenticationType,
                CustomClaimTypes.Name,
                CustomClaimTypes.Role);

            context.Validated(claimsIdentity);

            return Task.FromResult(0);
        }
    }
});

使用此代码:

services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options => 
        {
            options.Authority = Configuration["AuthorizationServer:Authority"];
            options.Audience = Configuration["AuthorizationServer:Audience"];

            options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                RoleClaimType = "CustomRole"
            };
        });