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

Ahm*_*adi 5 claims-based-identity oauth-2.0 owin asp.net-web-api2

OAuth 服务器使用以下不同的声明类型发出角色声明System.Security.Claims.ClaimTypes.Role

var adminRole = new Claim("CustomRole", "Admin");
context.Ticket.Identity.AddClaim(adminRole);
Run Code Online (Sandbox Code Playgroud)

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

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

[Authorize(Roles = "Admin")]
public IHttpActionResult SecureAction()
Run Code Online (Sandbox Code Playgroud)

Ahm*_*adi 2

OnValidateIdentity的函数中OAuthBearerAuthenticationProvider,我们可以ClaimsIdentity使用适当的RolaClaimType和重新绑定NameClaimType

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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)