您好,登錄后才能下訂單哦!
本篇文章為大家展示了使用ASP.NET Core怎么實(shí)現(xiàn)跨站登錄重定向,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
具體拿 ASP.NET Core 來說就是 CookieAuthenticationOptions.LoginPath
只能指定路徑,不能指定包含主機(jī)名的完整 url ,ASP.NET Core 會(huì)在重定向時(shí)自動(dòng)加上當(dāng)前請(qǐng)求的主機(jī)名。
services.AddAuthentication() .AddCookie(options => { options.LoginPath = "/account/signin"; });
ReturnUrl 查詢參數(shù)也只會(huì)包含路徑,不包含完整的 url 。
為了解痛,在 ASP.NET 時(shí)代我們服用的解藥要么是不用 ASP.NET 的登錄跳轉(zhuǎn)機(jī)制,要么通過專門的 UserController.Login Action 進(jìn)行二次跳轉(zhuǎn),在 ASP.NET Core 時(shí)代我們改服了 Middleware 的解藥,在專門的 Middleware 中進(jìn)行跳轉(zhuǎn)(也比較麻煩)。
昨天在閱讀了 ASP.NET Core Authenticaion 的源碼后,我們找到了一種新的解藥 —— 修改 CookieAuthenticationEvents.OnRedirectToLogin
委托實(shí)現(xiàn)跨站登錄重定向。
以下是新解藥制作方法。
在 Startup.ConfigureServices 中給 AddCookie 添加如下的配置代碼以使用修改后的 url 進(jìn)行重定向:
services.AddAuthentication() .AddCookie(options => { var originRedirectToLogin = options.Events.OnRedirectToLogin; options.Events.OnRedirectToLogin = context => { return originRedirectToLogin(RebuildRedirectUri(context)); }; });
RebuildRedirectUri 的實(shí)現(xiàn)代碼如下:
private static RedirectContext<CookieAuthenticationOptions> RebuildRedirectUri( RedirectContext<CookieAuthenticationOptions> context) { if (context.RedirectUri.StartsWith(ACCOUNT_SITE)) return context; var originUri = new Uri(context.RedirectUri); var uriBuilder = new UriBuilder(ACCOUNT_SITE); uriBuilder.Path = originUri.AbsolutePath; var queryStrings = QueryHelpers.ParseQuery(originUri.Query); var returnUrlName = context.Options.ReturnUrlParameter; var returnUrl = originUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped) + queryStrings[returnUrlName]; uriBuilder.Query = QueryString.Create(returnUrlName, returnUrl).ToString(); context.RedirectUri = uriBuilder.ToString(); return context; }
上述內(nèi)容就是使用ASP.NET Core怎么實(shí)現(xiàn)跨站登錄重定向,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。