1

我試圖讓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的建議將非常感激。

回答

2

身份服務器使用cookie認證在內部它轉換成401 302

我不認爲你可以app.UseIdentityServer()app.UseIdentityServerAuthentication()共同生活的緣故吧。

但是,您可以輕鬆找到解決方法。

最好的是(在本地主機例如身份服務器:5000和應用在本地主機:5001)來承載在單獨的應用程序身份服務器。它更適合的開放ID的概念連接,你可以在official GitHub

享受噸的例子或者你可以試着將Identity Server和AP​​I在不同的子路徑像本地主機: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(); 
    }); 

此外,這種方法更容易出錯,我寧願考慮單獨的應用程序。

+0

我無法使用UseWhen方法來工作,但將兩個組件分離爲單獨的系統完美運行。非常感謝您的幫助! –

相關問題