问题描述
我正在尝试在我的应用程序中同时设置令牌身份验证和cookie身份验证.
Im trying to setup Token authentication with cookie authentication on same time in my application.
我在asp.net core 2.0中创建了一个MVC项目,其中有要认证的单个用户帐户.也为用户设置角色.
I created a MVC project in asp.net core 2.0, with individual user accounts to auth. Setup roles to the users too.
如果我遵循Shawn Wildermuth的教程 ASP-NET-Core-2中的两个授权方案
If i follow this tutorial of Shawn Wildermuth Two-AuthorizationSchemes-in-ASP-NET-Core-2
一切正常,可以获取注册用户的令牌.但是,如果我在授权[Authorize(Roles ="Admin")]上使用Role属性,则会收到403响应.
Everything works fine to get the Token of the registered user. But if i use the Role attribute on authorize [Authorize(Roles="Admin")] im getting a 403 response.
我认为这是因为令牌未在auth上接收角色.
I think that is because the Token is not receiving the Role on auth.
如何设置?有什么办法可以在令牌过程中传递角色?
How to setup this? Is any way to pass the Roles on the Token process?
他正在使用这段代码来生成令牌:
To generate the token he is using this piece of code:
[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"); }
你们有什么主意吗?
谢谢
推荐答案
如果添加以下使用和代码,应该会有所帮助.
If you add the following using and code, that should help.
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)));
您会看到在Union中添加了类型为ClaimTypes.Role的角色,这将使它们可以在AuthorizeAttribute中使用
You can see the Union that adds the roles in with the type of ClaimTypes.Role, this will enable them to be used in the AuthorizeAttribute
HTH
这篇关于结合使用身份和令牌和cookie身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!