简体   繁体   English

基于角色的令牌ASP.net身份

[英]Role based tokens ASP.net Identity

I am using the standard ASP.net OWIN OAuth middleware system to authenticate local users with Bearer tokens. 我正在使用标准ASP.net OWIN OAuth中间件系统来使用Bearer令牌对本地用户进行身份验证。 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- 然后在我的System.Web.Http.AuthorizeAttribute实现中,我可以像这样检查声明:

//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 ) (摘自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);




    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM