[英]Getting 401 unauthorized ASP.NET CORE 6
我在 ASP.NET CORE 6 中实现了基于角色的身份验证,并且我从 Postman 获得了 401 Unauthorized。我已经包含了不记名令牌,我已经在 jwt.io 中检查过它并且它是有效的。 但它仍然显示 401 未经授权。 这是我的 startup.cs 文件
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.MapRazorPages();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
这是一个 controller 方法
[HttpGet("onlinedrivers"), Authorize]
public async Task<ActionResult> GetOnlineDrivers()
{
var result = await _driverServices.GetOnlineDrivers();
return Ok(result);
}
我不知道我做错了什么
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false // you dont want to validate lifetime
};
});
它已修复,发现我在创建令牌时注释掉了令牌到期日期。 感谢 gunr2171,我检查了日志,它说
Bearer error="invalid_token", error_description="The token has no expiration"
所以当我添加到期日期时,它起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.