Role based tokens ASP.net Identity

2019-07-31 08:54发布

问题:

I am using the standard ASP.net OWIN OAuth middleware system to authenticate local users with Bearer tokens. What I would like to do is is hand out role-based tokens for the same user account. eg.

           OAuth TokenA => General User Privileges 
UserA -> 
           OAuth TokenB => Admin User Privileges 

Is this supported in any way?

回答1:

I was able to solve this using the following method -

//ensure the token is a User role token only
identity.AddClaim(new Claim(ClaimTypes.Role, "User"));

Where 'identity' is an instance of

System.Security.Claims.Identity

Then in my System.Web.Http.AuthorizeAttribute implementation, I can check the claim like so-

//get claims of the Role type
var identity = (ClaimsIdentity)actionContext.RequestContext.Principal.Identity;
IEnumerable<Claim> claims = identity.Claims.Where(c => c.Type == ClaimTypes.Role);

//check if any claim for the User role, if so this is a non-privleged token
var nonPrivToken = claims.Any(c => c.Value == "User");


回答2:

You can add claims to the user just before the bearer token is generated. So if you change the things you put into, two different bearer token can be generated and consumed.

(From the taiseer-joudeh-blog)

 public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
         // Change the role and create new bearer token
        identity.AddClaim(new Claim("role", "user"));
        context.Validated(identity);




    }
}