Role based tokens ASP.net Identity

早过忘川 提交于 2019-12-11 09:57:16

问题


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




    }
}


来源:https://stackoverflow.com/questions/24071137/role-based-tokens-asp-net-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!