0
아래 방법의 맨 위에 권한 부여 태그없이 작동하는 JWT 토큰 작성 방법이 있습니다. 이전에 토큰을 구현하기 전에 작동하는 사용자 역할을 만들었습니다. 토큰 구현 방법 이후로 나는 역할에 의한 권한 부여를 구성 할 수 없었고, 코드는 JWT 토큰을 필요로하는 권한이 있다고 생각한다. 토큰을 우편 배달부로 전달하면 인증은 간단하게 [Authorize]
에서 작동합니다. 하지만 등록 된 사용자 만 사용할 수 있도록 토큰 생성 메소드를 제한해야합니다.JWT 토큰 작성 방법 승인 방법 (사용자 역할)
[Authorize(Roles = "Users")]
[HttpPost("api/auth/token")]
public async Task<IActionResult> CreateToken([FromBody]
CredentialViewModel model)
{
try
{
var user = await userManager.FindByNameAsync(model.UserName);
if (user != null)
{
if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
{
// Get the claims from the user
var userClaims = await userManager.GetClaimsAsync(user);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, user.APIKey.ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email??"")
}.Union(userClaims);
//*********************************
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _config["Tokens:Issuer"],
audience: _config["Tokens:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddDays(10),
signingCredentials: creds
);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
}
}
catch (Exception ex)
{
_logger.LogError($"Exception thrown while creating JWT: {ex}");
}
return BadRequest();
}
예를 들어, JSON 입력
{
"username" : "user02",
"password" : "test123"
}