我正在使用标准的ASP.net OWIN OAuth中间件系统来使用Bearer令牌对本地用户进行身份验证。我想要做的是为同一个用户帐户分发基于角色的令牌。例如。
OAuth TokenA => General User Privileges
UserA ->
OAuth TokenB => Admin User Privileges
这是否有任何支持?
答案 0 :(得分: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");
答案 1 :(得分:0)
您可以在生成承载令牌之前向用户添加声明。因此,如果您更改了所添加的内容,则可以生成并使用两个不同的承载令牌。
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);
}
}