[英]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.