我已经在 .Net core 1.1 中实现了基于 JWT 不记名令牌的身份验证和授权。我还实现了用于登录和注册的用户管理器。我使用以下代码将用户密码与 PasswordHash 匹配。
var userDetails = await _userManager.FindByNameAsync(username);
var result = await _signInManager.CheckPasswordSignInAsync(userDetails, password, lockoutOnFailure: false);
我在基于角色的授权中遇到问题。当我使用用户(用户类型角色)生成 JWT 令牌时,它工作正常并且只能访问 [Authorize(Roles = "User")] 属性方法或操作。但是当我使用 [Authorize(Roles = "Administrator")] 属性时,它同时由用户和管理员角色类型访问。下面的示例代码:
[Authorize(Roles = "Administrator, User")]
public class AnswersController : Controller
{
private readonly IAnswerService answerServices = null;
public AnswersController(IAnswerService _answerServices)
{
answerServices = _answerServices;
}
[Authorize(Roles = "Administrator")]
// GET: api/Answers
[HttpGet]
public async Task<IActionResult> Get()
{
var result = await answerServices.GetAll();
if (result == null)
{
return NotFound();
}
return Ok(result);
}
[Authorize(Roles = "User")]
// GET: api/Answers/5
[HttpGet("{id}")]
public async Task<IActionResult> Get([FromRoute] int id)
{
var result = await answerServices.GetByID(id);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
}
}