我在.Net核心1.1中实现了基于JWT承载令牌的身份验证和授权。我还实现了Usermanager登录和注册。我使用以下代码将用户密码与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);
}
}
}