令牌是通过以下方法生成的:
private string GenerateJwtToken(User user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var base64Key = _configuration["Jwt:Secret"];
try
{
var key = Convert.FromBase64String(base64Key);
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = _configuration["Jwt:Issuer"],
Audience = _configuration["Jwt:Audience"],
Subject = new ClaimsIdentity(
new Claim[]
{
new Claim(ClaimTypes.Name, user.Email),
new Claim("UserId", user.ID.ToString())
}
),
Expires = DateTime.UtcNow.AddDays(14),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
Security算法rithms.HmacSha256Signature
)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
catch (FormatException ex)
{
Console.WriteLine($"error converting Base64 string: {ex.Message}");
return null;
}
}
我在jwt.io上判断了一下,它说生成的令牌是有效的.
当我使用thunderclient到我的/user端点,通过在头中传递JWT令牌来获取用户时,我会得到Status:401 Unauthorized.
下面是我的POST方法:
[HttpPost]
[Authorize]
public async Task<ActionResult<UserDTO>> GetUserDTO()
{
Console.WriteLine("I GET USER");
try
{
var jwt = HttpContext.Request.Headers["Authorization"]
.ToString()
.Replace("Bearer ", string.Empty);
Console.WriteLine(jwt);
if (string.IsNullOrWhiteSpace(jwt))
{
return BadRequest("JWT token is missing.");
}
var loggedInUser = _userService.GetByJWT(jwt);
if (loggedInUser == null)
{
return BadRequest("Failed to get user.");
}
return Ok(loggedInUser.FirstName);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
当我go 掉[Authorize]
时,它就可以工作了,它可以从JWT载体中解析ID.
在program.cs
中,我有我的授权模式,并试图更改它,看看它是否与我的发行者或受众有问题?我将我的发行者值设置为我的应用程序名称,将受众值设置为API,因为它是将使用它的API.对吗?以下是模式:
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"])
),
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"]
};
});
builder.Services.AddAuthorization();
为什么我得到了未经授权的?
100 下面是我try 设置标题/授权的方法