在ASP.NET Core 3.1中使用Identity Server 4进行身份认证,如果JWT Bearer Token无法正常工作,可能是由于配置或代码问题引起的。以下是一些可能的解决方法:
确保Identity Server 4的配置正确:
确保ASP.NET Core应用程序的Startup.cs文件中正确配置了JWT Bearer认证:
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://identityserver.example.com";
options.RequireHttpsMetadata = false; // 仅在开发环境中使用
options.Audience = "api";
});
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseAuthorization();
// ...
}
确保API资源的配置正确:
// Config.cs
public static IEnumerable GetApiResources()
{
return new List
{
new ApiResource("api", "API Name")
{
Scopes = { "api.read", "api.write" } // 定义API资源的作用域
}
};
}
确保客户端的配置正确:
// Config.cs
public static IEnumerable GetClients()
{
return new List
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api.read", "api.write" } // 允许客户端请求的作用域
}
};
}
在API的Controller中使用[Authorize]属性标记需要进行身份认证的方法或控制器。
// MyController.cs
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class MyController : ControllerBase
{
// ...
}
这些解决方法可能有助于解决ASP.NET Core 3.1 + Identity Server 4中JWT Bearer Token无法工作的问题。请根据您的具体情况进行适当的调整和配置。
上一篇:ASP.NET Core 3.1 + CORS + Windows Authentication = 401 未经授权
下一篇:ASP.NET Core 3.1 - AddJwtBearer,在Fail时OnTokenValidated事件不遵守自定义消息。