oauth-2.0asp.net-web-api2owinclaims-based-identity

Using custom RoleClaimType on OAuthBearer middleware


The OAuth server issues role claims using different claim type from System.Security.Claims.ClaimTypes.Role:

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

How can I tell the OAuthBearerAuthentication middleware to use my custom role claim type so it gets the Authorize attribute to work:

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

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

Solution

  • In OnValidateIdentity function of OAuthBearerAuthenticationProvider, we can rebind ClaimsIdentity with appropriate RolaClaimType and 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);
            }
        }
    });