问题:AddJwtBearer()
失败,但是手动验证令牌有效。我正在尝试使用非对称RSA算法生成和验证JWT。
我可以使用此演示代码很好地生成JWT
[HttpPost("[action]")]
[Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> JwtBearerToken() {
AppUser user = await userManager.GetUserAsync(User);
using RSA rsa = RSA.Create(1024 * 2);
rsa.ImportRSAPrivateKey(Convert.FromBase64String(configuration["jwt:privateKey"]), out int _);
var signingCredentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256);
var jwt = new JwtSecurityToken(
audience: "identityapp",
issuer: "identityapp",
claims: new List<Claim>() {new Claim(ClaimTypes.NameIdentifier, user.UserName)},
notBefore: DateTime.Now,
expires: DateTime.Now.AddHours(3),
signingCredentials: signingCredentials
);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
return RedirectToAction(nameof(Index), new {jwt = token});
}
我还可以使用下面的演示代码验证令牌及其签名
[HttpPost("[action]")]
[ValidateAntiForgeryToken]
public IActionResult JwtBearerTokenVerify(string token) {
using RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey(Convert.FromBase64String(configuration["jwt:privateKey"]), out int _);
var handler = new JwtSecurityTokenHandler();
ClaimsPrincipal principal = handler.ValidateToken(token, new TokenValidationParameters() {
IssuerSigningKey = new RsaSecurityKey(rsa),
ValidAudience = "identityapp",
ValidIssuer = "identityapp",
RequireExpirationTime = true,
RequireAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateAudience = true,
}, out SecurityToken securityToken);
return RedirectToAction(nameof(Index));
}
但是,当命中受保护的端点时,验证失败(401)[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
来自HTTP标头的错误消息:Bearer错误=“ invalid_token”,error_description =“签名无效”
我的JWT承载身份验证配置在这里
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => {
using var rsa = RSA.Create();
rsa.ImportRSAPrivateKey(Convert.FromBase64String(Configuration["jwt:privateKey"]), out int _);
options.IncludeErrorDetails = true;
options.TokenValidationParameters = new TokenValidationParameters() {
IssuerSigningKey = new RsaSecurityKey(rsa),
ValidAudience = "identityapp",
ValidIssuer = "identityapp",
RequireExpirationTime = true,
RequireAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateAudience = true,
};
});
我可以使用对称密钥和HmacSha256轻松使它工作-但这不是我想要的。
使用此配置:
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = false;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(private_key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
});