我試圖讓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的建議將非常感激。
我無法使用UseWhen方法來工作,但將兩個組件分離爲單獨的系統完美運行。非常感謝您的幫助! –