c# - 使用 Identity Core 中的角色进行 JWT 授权
问题描述
我无法Roles
理解Identity Core
我的AccountController
样子是这样的,我Roles
在方法中添加了声明GenerateJWTToken
:
[HttpPost("Login")]
public async Task<object> Login([FromBody] LoginBindingModel model)
{
var result = await this.signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);
if (result.Succeeded)
{
var appUser = this.userManager.Users.SingleOrDefault(r => r.UserName == model.UserName);
return await GenerateJwtToken(model.UserName, appUser);
}
throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
}
[HttpPost("Register")]
public async Task<object> Register([FromBody] RegistrationBindingModel model)
{
var user = new ApplicationUser
{
UserName = model.UserName,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName
};
var result = await this.userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await this.signInManager.SignInAsync(user, false);
return await this.GenerateJwtToken(model.UserName, user);
}
throw new ApplicationException("UNKNOWN_ERROR");
}
private async Task<object> GenerateJwtToken(string userName, IdentityUser user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, userName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Role, Role.Viewer.ToString()),
new Claim(ClaimTypes.Role, Role.Developer.ToString()),
new Claim(ClaimTypes.Role, Role.Manager.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.configuration["JwtKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToDouble(this.configuration["JwtExpireDays"]));
var token = new JwtSecurityToken(
this.configuration["JwtIssuer"],
this.configuration["JwtIssuer"],
claims,
expires: expires,
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
从这段代码中,我的令牌与[Authorize]
控制器的属性完美配合。
我的问题是,在哪一步添加role
到我的注册user
使用(例如)[Authorize("Admin")]
?如何保存role
到数据库?
[Route("api/[controller]")]
[Authorize] //in this form it works ok, but how to add roles to it with JWT Token?
//how to register user to role and get this role to JWT Token?
[ApiController]
public class DefaultController : ControllerBase
我的ApplicationUser
:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
和枚举Roles
:
public enum Role
{
Viewer,
Developer,
Manager
}
如何将有关用户角色的信息保存到身份数据库,并在登录时将该角色获得正常工作的[Authorize]
属性?
编辑:
我想要做的是Roles
像我的枚举一样存储在用户中。我想将用户注册为Developer
等Manager
。我相信我可以通过ApplicationUser
添加Role
属性来做到这一点,但是我无法通过属性获得授权[Authorization(role)]
解决方案
您可以将内置角色管理与 ASP.NET Identity 一起使用。由于您使用的是 ASP.NET Core 2.1,您可以首先参考以下链接以启用身份系统中的角色:
https://stackoverflow.com/a/54069826/5751404
启用角色后,您可以注册角色/用户,然后向用户添加角色,例如:
private async Task CreateUserRoles()
{
IdentityResult roleResult;
//Adding Admin Role
var roleCheck = await _roleManager.RoleExistsAsync("Admin");
if (!roleCheck)
{
IdentityRole adminRole = new IdentityRole("Admin");
//create the roles and seed them to the database
roleResult = await _roleManager.CreateAsync(adminRole);
_roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "edit.post")).Wait();
_roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "delete.post")).Wait();
ApplicationUser user = new ApplicationUser {
UserName = "YourEmail", Email = "YourEmail",
};
_userManager.CreateAsync(user, "YourPassword").Wait();
await _userManager.AddToRoleAsync(user, "Admin");
}
}
因此,当该用户登录到您的应用程序时,您可以role
在 ClaimsPrincipal 中找到声明,并且该声明适用Authorize
于具有角色的属性。
推荐阅读
- r - 嵌套循环查找最新评论
- c++ - 在下面的代码中使用释放和移动的区别
- ruby-on-rails - 是否可以使用 Liquid shopify 读取本地文件内容并将其内容加载到页面中
- python - 我已经在我的电脑上尝试过,它运行良好,但在 pyschools 网站上仍然出现“浮点除以零”。为什么 ??:
- dart - 缺少 Getter 和 Setter 的具体实现
- dialogflow-es - 使用 java dialogflowv2 生成包含快速回复的 WebhookResponse
- sql - 我的数据只显示一个,但数据应该不止一个
- lambda - 使用 Terraform/CloudFormation/Something 有效地部署 lambdas(只部署那些改变的)
- python - 使用 map 函数根据字典转换列名的麻烦
- php - 运行新项目时找不到接口“Monolog\ResettableInterface”