1

我正在使用標準的ASP.net OWIN OAuth中間件系統使用持票人令牌對本地用戶進行身份驗證。我想要做的是爲相同的用戶帳戶提供基於角色的令牌。例如。基於角色的令牌ASP.net身份

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

這是支持任何方式嗎?

+0

http://www.c-sharpcorner.com/UploadFile/2b481f/Asp-Net-web-api-authorization-and-authontication/ - 或許這能夠幫幫我 – Tascalator

回答

1

我能夠這樣使用下面的方法來解決 -

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

您可以在持票人令牌之前向用戶添加聲明產生。所以如果你改變了你放入的東西,可以生成和使用兩個不同的持票人令牌。

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




    } 
} 
相關問題