我试图在我的应用程序中同时使用cookie身份验证设置令牌身份验证。
我在asp.net core 2.0中创建了一个MVC项目,其中包含要验证的个人用户帐户。也为用户设置角色。
如果我遵循Shawn Wildermuth Two-AuthorizationSchemes-in-ASP-NET-Core-2
的本教程一切正常,可以获得注册用户的令牌。但是,如果我在授权[Authorize(Roles =" Admin")]上使用Role属性,我会收到403响应。
我认为这是因为令牌没有在auth上接收角色。
如何设置?有没有办法在令牌过程中通过角色?
要生成令牌,他正在使用这段代码:
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> GenerateToken([FromBody] LoginViewModel model) { if (ModelState.IsValid) {
var user = await _userManager.FindByEmailAsync(model.Email);
if (user != null)
{
var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (result.Succeeded)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Tokens:Issuer"],
_config["Tokens:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
} }
return BadRequest("Could not create token"); }
你们有什么想法吗?
由于
答案 0 :(得分:2)
如果你使用和代码添加以下内容,那应该会有所帮助。
using System.Security.Claims;
...
var userRoles = await _userManager.GetRolesAsync(user);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
}.Union(userRoles.Select(m => new Claim(ClaimTypes.Role, m)));
您可以看到使用ClaimTypes.Role类型添加角色的Union,这将使它们能够在AuthorizeAttribute中使用
HTH