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

跨 .NET 版本實現單點登錄:MachineKey 統一、Cookie 共享、HttpModule 統一跳轉

     編輯:ASP.NET 基礎

核心難點

.NET 2.0 與 4.0+ 對 Forms 認證票據加密/解密算法默認不同,導致跨版本應用無法互相解密 Cookie。解決關鍵:**統一 MachineKey 驗證/解密金鑰與算法**。

1. 共用登錄頁代碼

protected void btnLogin_Click(object sender, EventArgs e)
{
    // 實際驗證用戶...
    FormsAuthentication.RedirectFromLoginPage("ejiyuan", false);
}

2. 統一 Web.config 關鍵配置(所有參與 SSO 的應用必須相同)

<authentication mode="Forms">
  <forms name=".ASPNET" 
         protection="All" 
         enableCrossAppRedirects="true" 
         loginUrl="Login.aspx" 
         timeout="2880" 
         path="/" 
         domain=".local.com" />
</authentication>

<machineKey 
    validationKey="F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902" 
    decryptionKey="F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902F8D923AC" 
    validation="SHA1" 
    decryption="3DES" />

關鍵屬性說明

  • `name=".ASPNET"`:Cookie 名稱統一。
  • `protection="All"`:加密+簽名驗證。
  • `domain=".local.com"`:二級域名共享 Cookie(需所有應用部署在 `*.local.com` 下)。
  • `enableCrossAppRedirects="true"`:允許跨應用重定向回原請求。
  • `machineKey`:**移除 `IsolateApps`**,顯式指定 `validationKey`、`decryptionKey`,算法指定 `SHA1`/`3DES`(跨版本兼容),**不要用 MD5/AES**(.NET 版本實現差異大)。

3. 無登錄頁應用:直接配置遠程登錄地址

<authentication mode="Forms">
  <forms name=".ASPNET" protection="All" enableCrossAppRedirects="true" 
         loginUrl="https://Sso2.local.com/Login.aspx" timeout="2880" path="/" domain=".local.com" />
</authentication>

4. 統一登錄跳轉 HttpModule(封裝 ReturnUrl 處理)

public class SsoLoginRedirectModule : IHttpModule
{
    public void Init(HttpApplication app)
    {
        app.EndRequest += OnEndRequest;
    }

    void OnEndRequest(object sender, EventArgs e)
    {
        HttpContext ctx = HttpContext.Current;
        if (ctx.Response.StatusCode == 302 && ctx.Response.RedirectLocation.Contains(FormsAuthentication.LoginUrl))
        {
            // 保證 ReturnUrl 為原始請求完整 URL
            ctx.Response.RedirectLocation = FormsAuthentication.LoginUrl + "?ReturnUrl=" + 
                HttpUtility.UrlEncode(ctx.Request.Url.OriginalString);
        }
    }

    public void Dispose() { }
}

5. 註冊模塊

<system.web>
  <httpModules>
    <add name="SsoModule" type="SsoModule.SsoLoginRedirectModule, SsoModule" />
  </httpModules>
</system.web>
' IIS7+ 集成模式還需在 <system.webServer>/<modules> 註冊

遷移到 ASP.NET Core 提示

Core 使用 **Data Protection** 系統替代 MachineKey,需配置共享金鑰環(Azure Blob、Redis、文件共享、Registry)並設置 `ApplicationDiscriminator` 相同,Cookie 共享同樣需統一 `Cookie.Name`、`Domain`、`DataProtectionProvider`。

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