萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

跨 .NET 版本實現單一登入 (SSO) 完整架構指南

核心原理:共享 Forms Authentication Cookie

多個 ASP.NET 應用程式 (不同版本 2.0/3.5/4.x) 透過**相同機器金鑰、相同 Cookie 設定**,即可共享驗證票據,達成單一登入。關鍵在於 `machineKey` 與 `forms` 設定完全一致。

統一 Web.config 設定 (所有子系統必須相同)

<configuration>
  <system.web>
    <!-- 1. 驗證模式 -->
    <authentication mode="Forms">
      <forms 
        name=".SSO_COOKIE"           <!-- 同一 Cookie 名稱 -->
        protection="All"             <!-- 加密+驗證 -->
        path="/"                     <!-- 根路徑共享 -->
        domain=".yourdomain.com"     <!-- 父網域共享 (需前綴 .) -->
        enableCrossAppRedirects="true" 
        timeout="480" 
        slidingExpiration="true" 
        requireSSL="true" />       <!-- 生產環境必開 -->
    </authentication>

    <!-- 2. 授權規則 -->
    <authorization>
      <deny users="?" />
    </authorization>

    <!-- 3. 機器金鑰 (核心:所有節點完全相同) -->
    <machineKey 
      validationKey="F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902" 
      decryptionKey="F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902F8D923AC"
      validation="SHA1" 
      decryption="AES" /> <!-- AES 比 3DES 安全 -->

    <!-- 4. .NET 4.0+ 相容性設定 -->
    <httpRuntime targetFramework="4.8" requestValidationMode="4.5" />
  </system.web>

  <!-- IIS 7+ 整合模式模組註冊 -->
  <system.webServer>
    <modules>
      <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
    </modules>
  </system.webServer>
</configuration>

關鍵設定說明

設定說明跨版本注意
validationKey簽章驗證金鑰 (128/256/384 hex chars)**必須手動指定固定值**,不可用 AutoGenerate
decryptionKey加密解密金鑰同前,**長度需符合演算法** (AES: 128/192/256 bits = 32/48/64 hex)
validationHMAC 演算法建議 SHA1 (相容) 或 HMACSHA256 (.NET 4.5+)
decryption加密演算法**AES** (預設 .NET 4.5+);舊版 3DES 僅為相容
domainCookie 作用域以 `.` 開頭表示包含所有子網域 (如 `.company.com`)
enableCrossAppRedirects允許跨應用程式重導向設為 `true` 讓 `FormsAuthentication.GetRedirectUrl` 正常運作

產生機器金鑰工具 (PowerShell)


function New-MachineKey {
    param([ValidateSet('AES','3DES')][string]$Decryption = 'AES',
          [ValidateSet('SHA1','HMACSHA256','HMACSHA384','HMACSHA512')][string]$Validation = 'SHA1')
    $valBytes = 64  # 512 bits for HMACSHA512
    $decBytes = if ($Decryption -eq 'AES') 32 else 24 # AES-256 / 3DES-192
    $val = [System.Web.Security.Membership]::GeneratePassword($valBytes, 0).Replace("'", "").Substring(0, $valBytes*2)
    $dec = [System.Web.Security.Membership]::GeneratePassword($decBytes, 0).Replace("'", "").Substring(0, $decBytes*2)
    return @"

"@
}
# 使用範例
New-MachineKey -Decryption AES -Validation SHA1

登入頁集中化架構 (無登入頁系統自動導向)




  

中央登入系統驗證成功後:


// SSO Login.aspx 核心邏輯
protected void btnLogin_Click(object sender, EventArgs e)
{
    if (ValidateUser(txtUser.Text, txtPass.Text))
    {
        // 建立共享 Ticket
        var ticket = new FormsAuthenticationTicket(1, txtUser.Text, DateTime.Now, 
            DateTime.Now.AddHours(8), chkPersist.Checked, "UserRole", FormsAuthentication.FormsCookiePath);
        string enc = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, enc)
        {
            Domain = FormsAuthentication.CookieDomain, // .yourdomain.com
            Path = FormsAuthentication.FormsCookiePath,
            HttpOnly = true,
            Secure = true
        };
        Response.Cookies.Add(cookie);

        // 導向原請求系統
        string returnUrl = Request.QueryString["ReturnUrl"] ?? "https://portal.yourdomain.com/";
        Response.Redirect(returnUrl);
    }
}

HttpModule 自動處理跨應用導向 (無登入頁系統)


public class SsoRedirectModule : IHttpModule
{
    public void Init(HttpApplication app)
    {
        app.EndRequest += (s, e) =>
        {
            var ctx = HttpContext.Current;
            if (ctx.Response.StatusCode == 302 
                && ctx.Response.RedirectLocation?.Contains(FormsAuthentication.LoginUrl) == true)
            {
                // 附帶原始請求網址作為 ReturnUrl
                string originalUrl = ctx.Request.Url.OriginalString;
                ctx.Response.RedirectLocation = 
                    FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(originalUrl);
            }
        };
    }
    public void Dispose() { }
}

註冊於各子系統 `web.config`:



  
    
  

跨 .NET 版本相容性陷阱與解決

問題原因解決
Ticket 解密失敗.NET 2.0 預設 3DES/SHA1,4.0+ 預設 AES/HMACSHA256**強制統一指定** `validation="SHA1" decryption="AES"` 並提供固定金鑰
Cookie 不共享domain/path/name 不一致集中管理 web.config 片段,部署時自動套用 (Config Transform / CI 變數)
角色資料遺失UserData 格式不一或 Principal 未重建統一 `Application_AuthenticateRequest` 解析 Ticket 重建 GenericPrincipal
閒置逾時不同步各系統獨立 slidingExpiration中央登入系統定期刷新 Cookie (AJAX heartbeat) 或接受略微差異

現代化替代方案:OpenID Connect / OAuth 2.0

新架構建議採用 **IdentityServer / Azure AD / Auth0 / Keycloak** 等標準 SSO 協定:

  • 協定標準化、跨平台 (Java, Node, Go, Mobile)
  • 支援 JWT Access Token + Refresh Token
  • 內建同意畫面、MFA、裝置授權、裝置流程
  • 單一登出、Token 撤銷、細粒度 Scope 授權

Forms Authentication SSO 適合**舊系統快速整合、純 .NET Framework 內網環境**;新專案請直接採用 OIDC/OAuth 2.0 現代標準。

copyright © 萬盛學電腦網 all rights reserved