[英]Asp.Net Role-based authentication using Security groups in Active Directory
[英]Role-based Authentication ASP.NET Core
我有一个使用JWT承载身份验证的Web API。 现在,我想知道如何使用asp.net核心上的JWT令牌实现基于角色的授权。 我想这aritcle使用基于角色的授权,但我没有得到太多的帮助。
有没有人有一篇不错的文章来研究或示例代码以实现基于角色的授权?
谢谢。
抱歉,我忘记了该帐户的密码,但是我已经有了一种解决方案,该解决方案涉及如何使用JWT令牌承载来实现基于角色的授权。
var user = _userRepository.CheckLogin(login);
if (user.UserID > 0)
{
var _userManager = HttpContext.User.Claims;
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Token:SecretKey"]));
var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha512);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.UniqueName, user.Username), // ClaimType.Name
new Claim(JwtRegisteredClaimNames.Email, user.EmailAddress), // ClaimType.EmailAddress
new Claim(JwtRegisteredClaimNames.NameId, user.UserID.ToString()), // ClaimType.NameIdentifier
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), // jti
new Claim(JwtRegisteredClaimNames.Actort, user.UserKey), // ClaimType.Actor
new Claim(ClaimTypes.Role, user.Type) // ClaimType.Role add role for authorization.
};
var stringToken = new JwtSecurityToken(
_configuration["Token:Issuer"],
_configuration["Token:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(Convert.ToInt32(_configuration["Token:ExpirationMinutes"])),
notBefore: DateTime.Now,
signingCredentials: credentials
);
var userToken = new JwtSecurityTokenHandler().WriteToken(stringToken);
return Ok(new { token = userToken });
}
在声明列表中添加ClaimTypes.Role
将解决此问题,现在您可以在控制器中使用[Authorize(Roles = "???")]
。
我希望这将对使用JWT Bearer身份验证添加角色的所有人有所帮助。
我已经在带有自定义表的asp.net核心上使用JWT令牌实现了基于角色的授权。 我将示例工作源代码放在Github上,并在medium上进行了详细解释。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.