首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

FormsAuthentication 跨子域名登入:讓 ReturnUrl 使用絕對路徑的優雅解法

     編輯:關於ASP.NET

場景:主站 i.cnblogs.com 登入頁指向 passport.cnblogs.com/login.aspx。預設 FormsAuthentication 重導向時,ReturnUrl 僅帶相對路徑(如 /post/list),導致登入後無法正確返回原站點。

傳統繞道法

在主站建立中轉登入頁,轉址時手動組裝絕對 ReturnUrl:

return Redirect("https://passport.cnblogs.com/login.aspx?ReturnUrl=" 
  + HttpUtility.UrlEncode("https://" + Request.Url.Host) + ReturnUrl);

優雅解法:攔截 FormsAuthenticationModule 事件

FormsAuthenticationModule.OnAuthenticate 事件可讓我們在驗證管線中修改重導向 URL。實作步驟:

  1. 建立自訂 IHttpModule 掛載至管線。
  2. 在 Init 訂閱 FormsAuthenticationModule.Authenticate 事件。
  3. 事件處理器中檢查 Response.RedirectLocation,若含 ReturnUrl 參數則替換為絕對路徑。

核心程式碼概念:

void OnAuthenticate(object sender, FormsAuthenticationEventArgs e) {
  var context = HttpContext.Current;
  if (context.Response.RedirectLocation != null && 
      context.Response.RedirectLocation.Contains(FormsAuthentication.ReturnUrlVar)) {
    // 解析並重建絕對 ReturnUrl
    var uriBuilder = new UriBuilder(context.Request.Url) { Path = ..., Query = ... };
    context.Response.RedirectLocation = uriBuilder.Uri.AbsoluteUri;
  }
}

此法集中處理,不污染業務邏輯,且支援多子域名部署。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved