当ASP.NET Core 5 Angular模板中的应用程序在刷新时返回401未经授权错误时,可能是因为认证令牌在刷新时丢失了。为了解决这个问题,可以采取以下措施:
export function tokenGetter() {
return localStorage.getItem('access_token');
}
...
JwtModule.forRoot({
config: {
tokenGetter,
allowedDomains: ['example.com'],
disallowedRoutes: ['example.com/examplebadroute/'],
},
}),
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseAuthentication();
...
}
[Authorize]
[HttpGet]
public IActionResult Get()
{
...
}
这些措施应该可以解决ASP.NET Core 5 Angular模板中的应用程序在刷新时返回401未经授权错误的问题。