[英]"Authorization failed. AuthenticationScheme: AzureADJwtBearer was challenged" in ASP.NET Core 3.1 Web API - 401 Unauthorized
[英]How to make ASP.Net Core Web API Identity return a 401 on unauthorized
我正在尝试使ASP.net核心Web api JSON Web令牌身份验证正常工作。 我已经成功地将IdentityServer4与该应用程序集成在一起,并且它正在成功处理基于ASP.net Core Identity的登录。
但是,每当身份验证失败时,API都会返回302结果,尝试将客户端重定向到登录页面。 但是,这是一个纯Web API,没有用户页面或用户应该直接进行交互的任何内容。
如何使系统返回401,而不是尝试重定向到登录页面?
ConfigureServices的标识部分如下所示:
// ASP.net Identity
var identityBackingStoreConnectionString = configuration["identity:backingStore"];
services
.AddIdentityWithMongoStoresUsingCustomTypes<MyApplicationUser, IdentityRole>(
identityBackingStoreConnectionString)
.AddDefaultTokenProviders();
services.AddSingleton<IClientStore, MyIdentityStore>();
// IdentityServer4
services.AddIdentityServer().AddTemporarySigningCredential()
.AddInMemoryApiResources(MyResourceStore.GetAllResources())
.AddAspNetIdentity<MyApplicationUser>()
.AddTemporarySigningCredential();
配置的相关(我认为)部分如下所示:
app.UseIdentity();
app.UseIdentityServer();
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
{
Authority = "http://localhost:5000/",
RequireHttpsMetadata = false,
ApiName = "myapi",
AutomaticAuthenticate = true,
JwtBearerEvents = new JwtBearerEvents()
{
OnAuthenticationFailed = async context => context.Response.StatusCode = 401
}
});
app.UseMvc();
如您所见,我尝试覆盖OnAuthenticationFailed事件,但无济于事。
任何有关如何使系统返回401的建议将不胜感激。
身份服务器在内部使用cookie身份验证,它将401转换为302。
我认为您不能因此使app.UseIdentityServer()
和app.UseIdentityServerAuthentication()
一起生活。
但是,您可以轻松找到解决方法。
最好是将身份服务器托管在单独的应用程序中(例如,身份服务器位于localhost:5000和应用程序位于localhost:5001 )。 它更适合开放ID连接的概念,您可以在官方GitHub上欣赏大量示例
或者,您可以尝试使用app.UseWhen
将身份服务器和API放在不同的子路径(例如localhost:5000 / idsrv和localhost:5000 / api)中。 例如
app.UseWhen(
c => c.Request.Path.StartsWithSegments(new PathString("/api")),
branch => {
branch.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
{
Authority = "http://localhost:5000/idsrv",
RequireHttpsMetadata = false,
ApiName = "myapi",
AutomaticAuthenticate = true,
} );
branch.UseMvc();
});
app.UseWhen(
c => c.Request.Path.StartsWithSegments(new PathString("/idsrv")),
branch => {
branch.UseIdentityServer();
branch.UseMvc();
} );
同样,这种方法更容易出错,我宁愿考虑使用单独的应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.