我在使用
Microsoft.AspNetCore.Authentication.JwtBearer 8.0.3
时遇到错误。以前我们在.Net 6,我们升级到.Net 8并升级了nuget包,之后我遇到了这个错误。虽然它与 Microsoft.AspNetCore.Authentication.JwtBearer 7.0.17
配合得很好。
错误:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Wed, 17 Apr 2024 13:48:59 GMT
Server: Kestrel
WWW-Authenticate: Bearer error="invalid_token"
Content-Length: 0
}}
我可以成功获取令牌,但它没有授权。
下面的代码用于生成 JWT 的令牌 .
[HttpPost]
public IActionResult getToken(TokenCredential _tokenCred)
{
IActionResult result = null;
try
{
if (_tokenCred.Key.Equals(_configuration["Jwt:Key"]) && _tokenCred.Secret.Equals(_configuration["Jwt:Secret"]))
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:JwtKey"]));
var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_configuration["Jwt:Issuer"],
_configuration["Jwt:Audience"],
claims,
expires: DateTime.UtcNow.AddMinutes(Int16.Parse(_configuration["Jwt:expiresInMinutes"])),
signingCredentials: signIn);
string _token = new JwtSecurityTokenHandler().WriteToken(token);
result = Ok(_token);
}
else
{
result = Unauthorized();
}
}
catch (Exception ex)
{
}
return result;
}
尝试使用 SecurityTokenDescriptor 类来创建安全令牌,
包含一些用于创建安全令牌的信息。
尝试一下:
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:JwtKey"]));
var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var tokenDescriptor1 = new SecurityTokenDescriptor {
Issuer = _configuration["Jwt:Issuer"],
Audience = _configuration["Jwt:Audience"],
Subject = new ClaimsIdentity(claims),
Expires= DateTime.UtcNow.AddMinutes(Int16.Parse(_configuration["Jwt:expiresInMinutes"])),
SigningCredentials= signIn };
var tokenObject1 = new JwtSecurityTokenHandler().CreateToken(tokenDescriptor1);
string _token = new JwtSecurityTokenHandler().WriteToken(tokenObject1);