OAuth 2.0 Code Flow / IdentityServer4 不能從認證伺服器成功跳轉回客戶端的問題
阿新 • • 發佈:2020-11-03
場景一:Mac ,visual studio for mac,Asp.net Core 3.1 ,Identityserver4(4.1.1)
採用 Client Credentails、Resource Owner Password Credentails授權型別時,均可以實現遠端認證。
但採用 Authorization Code 對Web app(客戶端)授權時,客戶端可以順利跳轉到Identityserver4,在認證伺服器上輸入使用者名稱密碼登入後,並不能成功跳轉回客戶端。檢視日誌並沒有報錯,跟蹤Identityserver4官方模板下的程式碼,也不能找到錯誤。
在Identityserver4的官方文件中也沒有找到相關問題的說明,只是看到了“推薦使用IIS...”,
無奈只能轉到 windows開發環境,但完成程式碼的相關程式碼轉換後再次除錯時,仍然是同樣的問題。
在網上查了相關資料,看了相關的解決方案,最終也沒有找到解決問題的辦法。
決定基於OAuth 2.0自己寫程式碼,在windows環境下,搭建了新的場景。
場景二:win10,visual studio 2019,asp.net core 3.1
仍然被卡在由認證服務端跳轉回客戶端上。
/// <summary> /// 引數命名需要符合OAuth 2.0的規範,客戶端只要遵行這個協議可以獲得認證服務 /// 響應客端:config.AuthorizationEndpoint = "https://localhost:50000/OAuth/Authorize"; /// </summary> /// <param name="response_type">認證流程型別 </param> /// <param name="client_id"></param> /// <param name="redirect_uri"></param> /// <param name="scope">請求範圍,如email\等claim</param> ///<param name="state">隨機生成的字串用來返回同一客戶端</param> /// <returns></returns> [HttpGet] public IActionResult Authorize( string response_type, string client_id, string redirect_uri, string scope, string state ) { var query = new QueryBuilder(); query.Add("redirectUri", redirect_uri); query.Add("state", state); return View(model:query.ToString()); } /// <summary> /// 引數命名符合OAuth 2.0 /// </summary> /// <param name="userName"></param> /// <param name="redirectUri"></param> /// <param name="state"></param> /// <returns></returns> [HttpPost] public IActionResult Authorize( string userName, string redirectUri, string state) { const string code = "anyStringCanBeTheCode"; var query = new QueryBuilder(); query.Add("code", code); query.Add("state", state); var afterLoginRedirectURL = $"{redirectUri}{query.ToString()}";//這個地址怎麼也跳不回去 return Redirect(afterLoginRedirectURL); }
但這時可以看到相關錯誤資訊:
An unhandled exception occurred while processing the request. Exception: Correlation failed. Unknown location Exception: An error was encountered while handling the remote login. Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler<TOptions>.HandleRequestAsync() Stack Query Cookies Headers Routing Exception: Correlation failed. Show raw exception details Exception: An error was encountered while handling the remote login. Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler<TOptions>.HandleRequestAsync() Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) Show raw exception details
報出錯誤來了,相信可以很快解決。