多個 ASP.NET 應用程式 (不同版本 2.0/3.5/4.x) 透過**相同機器金鑰、相同 Cookie 設定**,即可共享驗證票據,達成單一登入。關鍵在於 `machineKey` 與 `forms` 設定完全一致。
<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) |
| validation | HMAC 演算法 | 建議 SHA1 (相容) 或 HMACSHA256 (.NET 4.5+) |
| decryption | 加密演算法 | **AES** (預設 .NET 4.5+);舊版 3DES 僅為相容 |
| domain | Cookie 作用域 | 以 `.` 開頭表示包含所有子網域 (如 `.company.com`) |
| enableCrossAppRedirects | 允許跨應用程式重導向 | 設為 `true` 讓 `FormsAuthentication.GetRedirectUrl` 正常運作 |
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);
}
}
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`:
| 問題 | 原因 | 解決 |
|---|---|---|
| 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) 或接受略微差異 |
新架構建議採用 **IdentityServer / Azure AD / Auth0 / Keycloak** 等標準 SSO 協定:
Forms Authentication SSO 適合**舊系統快速整合、純 .NET Framework 內網環境**;新專案請直接採用 OIDC/OAuth 2.0 現代標準。