【发布时间】:2019-09-17 22:18:58
【问题描述】:
我无法理解Identity Core 中的Roles
我的AccountController 看起来像这样,我在GenerateJWTToken 方法的声明中添加了Roles:
[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)] 获得授权
【问题讨论】:
-
@WiktorZychla 感谢您的反馈,但我的项目是
core 2.1 -
查看我的answer
-
@MuhammadHannan 感谢您的建议,但我认为并非如此。我对我的问题进行了编辑
-
@michasaucer 我也有同样的问题!!你找到解决这个问题的方法了吗?任何提示或文档链接都会有所帮助。
标签: c# asp.net-core asp.net-identity claims-based-identity