我使用标准的ASP.net OWIN OAuth中间件系统来使用承载令牌对本地用户进行身份验证。我想做的是为同一用户帐户分发基于角色的令牌。如。
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"));
其中'identity'是
的实例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);
}
}