在 Blazor WASM 应用程序中,当使用 Identity Server 5 发送 API 请求时,可能会遇到以下错误:
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'
这是因为 Identity Server 5 要求所有 API 请求都必须通过身份验证才能访问。为了解决这个问题,我们可以通过以下步骤授权 API 请求:
添加以下 NuGet 包: Microsoft.AspNetCore.Authentication.JwtBearer Microsoft.AspNetCore.Authorization
在 appsettings.json 文件中添加 Identity Server 的配置信息:
"IdentityServer": {
"Authority": "http://localhost:5000",
"ApiName": "MyApi",
"RequireHttpsMetadata": false
}
其中,“Authority”代表 Identity Server 的地址,“ApiName”代表 API 的名称,由 Identity Server 进行授权。
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = Configuration["IdentityServer:Authority"];
options.ApiName = Configuration["IdentityServer:ApiName"];
options.RequireHttpsMetadata = Configuration.GetValue("IdentityServer:RequireHttpsMetadata");
});
services.AddAuthorization();
[Authorize]
[HttpGet("/api/sample")]
public async Task GetSampleData()
{
// API 逻辑
}
这将确保只有经过身份验证的用户才能访问该方法。