簡體   English   中英

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

[英]Role based tokens ASP.net Identity

我正在使用標准ASP.net OWIN OAuth中間件系統來使用Bearer令牌對本地用戶進行身份驗證。 我想做的是為同一用戶帳戶分發基於角色的令牌。 例如。

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

是否以任何方式支持?

我可以使用以下方法解決此問題-

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

其中“身份”是

System.Security.Claims.Identity

然后在我的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");

您可以在生成承載令牌之前向用戶添加聲明。 因此,如果您更改放入的物品,則會生成並使用兩個不同的承載令牌。

(摘自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