如何为CookieAuthentication中间件解密ASP.NET Cookie

时间:2017-07-14 15:41:27

标签: asp.net-mvc owin

我想要解密由CookieAuthentication中间件默认命名为“.AspNet.Cookies”的OWIN cookie。

1 个答案:

答案 0 :(得分:0)

请参阅此链接:https://lbadri.wordpress.com/2014/11/23/reading-katana-cookie-authentication-middlewares-cookie-from-formsauthenticationmodule/

// Get Cookie
var request = HttpContext.Request;
var cookie = request.Cookies.Get(".AspNet.Cookies");
var ticket = cookie.Value;

// 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
bytes = System.Web.Security.MachineKey.Unprotect(bytes,
    typeof(CookieAuthenticationMiddleware).FullName,
    "Cookies", // See below
    "v1");

bytes 参数后传递给Unprotect的参数称为目的,需要匹配预期的参数才能正确解密。否则你会得到 CryptographicException

" Cookies"参数匹配:

中的值
(new CookieAuthenticationOptions()).AuthenticationType

解密后,您可以按照上面的链接中的说明构建ClaimsIdentity,或者将字节转储到字符串中。