2

我們有一個使用OpenIdDict進行身份驗證的asp.net核心Web應用程序。我注意到,我未經身份驗證的Ajax調用返回了200以及我們的登錄表單。從我讀過的這是預期的行爲,因爲OpenIdDict處理請求,然後ASP.NET核心處理它並返回200. ASP.NET核心處理它,因爲在Startup.cs中調用'UseIdentity()'。我所見過的所有OpenIdDict實例都調用了'UseIdentity'。我有2個問題。使用openIdDict我們必須在Startup.cs中使用'UseIdentity()'嗎?

  1. 如果我不想ASP.NET核心來處理我的請求,我可以只刪除「UseIdentity()」?我試過了,現在我得到了401而不是200.這樣做有沒有什麼壞處,或者OpenIdDict是否需要'UseIdentity()'?
  2. 如果我不想失去重定向登錄UI視圖的能力是完成此操作以覆蓋OnRedirectToLogin的最好/最簡單/最安全的方法?下面的代碼示例:

options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents { OnRedirectToLogin = ctx => { if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == (int) HttpStatusCode.OK) { ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized; } else { ctx.Response.Redirect(ctx.RedirectUri); } return Task.FromResult(0); } };

代碼示例源:https://devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/

這個問題在這裏的進一步討論:https://github.com/aspnet/Security/issues/804

回答

3

是否OpenIdDict需要 'UseIdentity()'?

號,由app.UseIdentity()引擎蓋下注冊的餅乾中間件不直接使用OpenIddict,所以調用此方法不需要OpenIddict才能正常工作。也就是說,如果您使用依靠cookie身份驗證的ASP.NET Core Identity功能(幾乎所有的東西都在AccountController/ManageController),那麼是的,您必須使用app.UseIdentity()

所有我見過OpenIdDict呼叫「UseIdentity」

對於不使用app.UseIdentity(),你可以在the official password flow sample看一看或閱讀this blog post樣本的例子,顯示瞭如何在沒有ASP.NET Core Identity的情況下使用OpenIddict。

如果我不想失去重定向登錄UI視圖的能力,是完成此操作以覆蓋OnRedirectToLogin的最佳/最簡單/最安全的方法?

這絕對有效,但我個人選擇了一個更安全的選項,即使用管道分支來排除由app.UseIdentity()註冊的cookie中間件。這不僅可以防止身份劫持你的API返回的401級響應,同時也避免了XSRF攻擊的HttpContext.User無法從cookie中提取的身份來填充:

app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch => 
{ 
    branch.UseIdentity(); 
}); 

一個完整的樣本見https://github.com/openiddict/openiddict-samples/blob/master/samples/CodeFlow/AuthorizationServer/Startup.cs#L141-L158

+0

這很好。謝謝! – Bloodhound

+0

您是否有示例項目或指南,可以使用Core 2.0和OpenIdDict 2.x做同樣的事情? – Bloodhound

+1

所有OpenIddict示例已更新爲2.x:https:// github。COM/openiddict/openiddict樣本。遺憾的是,2.x中不再支持基於路徑的身份驗證中間件選擇,並且推薦使用'[Authorize(AuthenticationSchemes =「Bearer」)]方法。閱讀https://github.com/aspnet/Announcements/issues/262瞭解更多信息。 – Pinpoint

相關問題