You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解密ASP.NET FormsAuthentication Cookie?Unprotect参数报错求助

解决旧版ASP.NET WebForms解密FormsAuthentication Cookie的参数问题

你猜得没错,报错确实是因为MachineKey.Unprotect的用途参数(purpose)和FormsAuthentication加密Cookie时用的不匹配——Owin的参数完全不适用于传统FormsAuthentication场景。

正确的参数设置

传统ASP.NET WebForms的FormsAuthentication在加密身份验证票证时,使用的固定用途参数是"FormsAuthentication",所以解密时必须传递这个值:

修正后的解密代码:

string ticket = Request.Cookies[".ASPXAUTH_xxx"].Value.ToString();
// Format Cookie to be converted
ticket = ticket.Replace('-', '+').Replace('_', '/');
var padding = 3 - ((ticket.Length + 3) % 4);
if (padding != 0)
    ticket = ticket + new string('=', padding);
var bytes = Convert.FromBase64String(ticket);

// Decrypt - 使用正确的purpose参数
bytes = System.Web.Security.MachineKey.Unprotect(bytes, "FormsAuthentication");

更简便的替代方案

其实完全不用手动处理Base64转换和填充,直接用FormsAuthentication.Decrypt方法即可,这是官方专门为FormsAuthentication Cookie提供的解密方法:

HttpCookie authCookie = Request.Cookies[".ASPXAUTH_xxx"];
if (authCookie != null)
{
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
    // 这里可以直接获取票证里的用户信息,比如ticket.Name、ticket.UserData等
}

这个方法会自动处理Cookie值的Base64编码转换、解密等所有步骤,比手动调用MachineKey.Unprotect更可靠也更简洁。

内容的提问来源于stack exchange,提问作者Robin Sun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:24:56