如何使ASP.Net核心Web API身份返回401未经授权
问题描述:
我试图让ASP.net核心Web API JSON Web令牌身份验证正常工作。我已经到了成功将IdentityServer4与应用程序集成的地步,并且它正在成功处理基于ASP.net Core Identity的登录。如何使ASP.Net核心Web API身份返回401未经授权
但是,无论身份验证何时失败,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()
共同生活的缘故吧。
但是,您可以轻松找到解决方法。
最好的是(在本地主机例如身份服务器:5000和应用在本地主机:5001)来承载在单独的应用程序身份服务器。它更适合的开放ID的概念连接,你可以在official GitHub
享受吨的例子或者你可以试着将Identity Server和API在不同的子路径像本地主机:5000/idsrv和本地主机:5000/API使用app.UseWhen
。例如
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();
});
此外,这种方法更容易出错,我宁愿考虑单独的应用程序。
我无法使用UseWhen方法来工作,但将两个组件分离为单独的系统完美运行。非常感谢您的帮助! –