我正在生成 JWT 令牌,然后尝试通过它进行授权,但我仍然收到 401 Unauthorized 这就是我生成 JWT 的方式:
string IAccountService.GenerateJwt(LoginDto dto)
{
var user = _context.Users.FirstOrDefault(u => u.EMail == dto.Email);
if (user == null)
{
throw new BadRequestException("Invalid user name or password", new Exception());
}
var resault = _passwordHasher.VerifyHashedPassword(user, user.Password, dto.Password);
if (resault == PasswordVerificationResult.Failed)
{
throw new BadRequestException("Invalid user name or password", new Exception());
}
var claims = new List<Claim>() {
// new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
//new Claim(ClaimTypes.Name, user.Name)
new Claim("Id", user.Id.ToString()),
new Claim("Name", user.Name)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("JwtSettings:Token").Value!));
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: cred
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
这是我的程序.cs:
builder.Services.AddAuthentication().AddJwtBearer();
...
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
我正在使用邮递员并选择不记名令牌,然后从 API 传递令牌
我尝试过这个https://nestenius.se/2023/06/02/debugging-jwtbearer-claim-problems-in-asp-net-core/ 输出: 但当我尝试索赔时却什么也没显示。
我已经解码了您提供的token,这表明您的JWT生成方法是正确的。令牌包含声明:id 和 name。因此,使用postman进行API测试时,请确认是否使用了最新的token。 如果您使用最新的token进行API测试后问题仍然存在,则在解析token的过程中,您需要使用与生成token时相同的配置来验证token。 TokenValidationParameters 是一组用于验证 JWT 令牌的参数。它包含一系列属性,指定验证 JWT Token 时的各种设置,例如签名密钥、颁发者验证、受众验证、生命周期验证等,因此在生成令牌时需要使用相同的配置来验证令牌卡,这里有一个例子,你可以作为参考:
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = configuration["JWT:ValidAudience"],
ValidIssuer = configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"]))
};