简体   繁体   中英

Role based tokens ASP.net Identity

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?

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");

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);




    }
}

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