我想要解密由CookieAuthentication中间件默认命名为“.AspNet.Cookies”的OWIN cookie。
答案 0 :(得分:0)
// 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,或者将字节转储到字符串中。