Forms 驗證核心設定集中在 web.config <forms> 元素。本文詳細說明各屬性用途、Cookie 保護機制 (驗證/加密)、FormsAuthenticationTicket 結構與序列化細節。
<authentication mode="Forms">
<forms name="MyAppCookie"
loginUrl="Login.aspx"
timeout="60"
slidingExpiration="true"
path="/"
protection="All"
requireSSL="false"
cookieless="UseDeviceProfile"
domain=""
enableCrossAppRedirects="false" />
</authentication>
| 屬性 | 預設值 | 說明 |
|---|---|---|
| name | .ASPXAUTH | Cookie 名稱,多應用程式部署同網域時需唯一化避免衝突 |
| loginUrl | login.aspx | 未驗證使用者存取受保護資源時導向頁面 |
| timeout | 30 (分鐘) | Ticket/逾期時間;slidingExpiration="true" 時每次請求重置 |
| slidingExpiration | true | true:活躍延長;false:固定期限 |
| path | / | Cookie 路徑,通常保持根路徑 |
| protection | All | All=驗證+加密;Validation=僅驗證;Encryption=僅加密;None=無保護 |
| requireSSL | false | true 時僅 HTTPS 傳送 Cookie |
| cookieless | UseDeviceProfile | UseUri/UseDeviceProfile/AutoDetect/Never:無 Cookie 時將 Ticket 嵌入 URL |
| domain | (空) | 跨子網域共享 Cookie (如 .example.com) |
| enableCrossAppRedirects | false | 允許跨應用程式重導並保持驗證 |
machineKey validation="MD5") 產生 MAC 附加 Ticket 尾端,防篡改。machineKey validation="3DES") 加密 Ticket 內容,防竊取。machineKey 必須一致,否則解密/驗證失敗。
public sealed class FormsAuthenticationTicket
{
public int Version { get; } // 1
public string Name { get; } // 使用者名稱
public DateTime IssueDate { get; } // 簽發時間
public DateTime Expiration { get; } // 到期時間 (UTC)
public bool IsPersistent { get; } // 是否持久 Cookie
public string UserData { get; } // 自訂資料 (如 UserId|Roles|Permissions)
public string CookiePath { get; } // Cookie 路徑
// 內部:序列化為字串 → 加密 → Base64 → Cookie 值
}
UserId|Role1,Role2|Perm1,Perm2 或 JSON。UserData 宜精簡,大量權限改用快取/資料庫查詢。UserData。/ (F(xxxx))/SecurePage.aspx。