我有两台服务器,一台使用jsonwebtoken生成JWT,另一台运行ASP.NET6。第一个服务器使用以下代码(TS)
import jwt from "jsonwebtoken"
const payload = {
iss: "identity.example.com",
exp: getTimeNow() + 5 * 60 * 1000,
sub: account.user_id,
aud: "store.example.com",
exc: item.id
}
res.status(200).json({
code: 200,
message: "",
data: {
jwt: jwt.sign(payload, process.env.JWT_SIGNING_KEY!, { // The key is set, ! is used just to prevent typescript from throwing an error
algorithm: "HS256"
})
}
})
字符串
ASP.NET服务器的Program.cs文件已按如下方式配置
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "identity.example.com",
ValidAudience = "store.example.com",
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("KEY")) // The key is the same used by the TS server
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
型
然而,当我向ASP.NET核心服务器发送请求时,总是得到一个401错误。我使用Authorization头发送令牌:Authorization: Bearer token_value
的。
我想知道为什么这不起作用,因为JWT应该是通用的,而ASP.NET核心只接受自己生成的JWT。
1条答案
按热度按时间l7wslrjt1#
感谢@Prolog注解,我发现问题在于TS服务器以毫秒而不是秒为单位设置
exp
值。