.NET 2.0 與 4.0+ 對 Forms 認證票據加密/解密算法默認不同,導致跨版本應用無法互相解密 Cookie。解決關鍵:**統一 MachineKey 驗證/解密金鑰與算法**。
protected void btnLogin_Click(object sender, EventArgs e)
{
// 實際驗證用戶...
FormsAuthentication.RedirectFromLoginPage("ejiyuan", false);
}
<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" />
<authentication mode="Forms">
<forms name=".ASPNET" protection="All" enableCrossAppRedirects="true"
loginUrl="https://Sso2.local.com/Login.aspx" timeout="2880" path="/" domain=".local.com" />
</authentication>
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() { }
}
<system.web>
<httpModules>
<add name="SsoModule" type="SsoModule.SsoLoginRedirectModule, SsoModule" />
</httpModules>
</system.web>
' IIS7+ 集成模式還需在 <system.webServer>/<modules> 註冊
Core 使用 **Data Protection** 系統替代 MachineKey,需配置共享金鑰環(Azure Blob、Redis、文件共享、Registry)並設置 `ApplicationDiscriminator` 相同,Cookie 共享同樣需統一 `Cookie.Name`、`Domain`、`DataProtectionProvider`。