[英]How to decrypt .AspNetCore.Identity.Application cookie in ASP.NET Core 3.0?
I'd like to manually decrypt the .AspNetCore.Identity.Application
cookie that gets stored by ASP.NET Core 3.0.0 to see exactly what information it contains.我想手动解密由 ASP.NET Core 3.0.0 存储的.AspNetCore.Identity.Application
cookie,以查看它包含的确切信息。 I understand that Microsoft have quite significantly changed how this is done between ASP.NET Core 2.2 and 3.0, so now that 3.0 has been released to general availability, I'd like to know: how can I manually decrypt this cookie in my application code in Core 3.0?我知道微软在 ASP.NET Core 2.2 和 3.0 之间已经大大改变了这是如何完成的,所以现在 3.0 已经发布到普遍可用,我想知道:如何在 Core 的应用程序代码中手动解密这个 cookie 3.0?
This is how you can decrypt a cookie based on CookieAuthenticationHandler这是基于CookieAuthenticationHandler解密 cookie 的方法
public class Startup
{
private CookieAuthenticationOptions _storedOption;
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddCookie(option =>
{
_storedOption = option;
});
}
public AuthenticationTicket Decrypt(HttpContext context, string cookie)
{
AuthenticationTicket ticket = _storedOption.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding(context));
return ticket;
}
public string DecryptRaw(HttpContext context, string cookie)
{
IDataProtectionProvider dataProtectionProvider = _storedOption.DataProtectionProvider;
IDataProtector protector = dataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2");
string purpose = GetTlsTokenBinding(context);
if (!string.IsNullOrEmpty(purpose))
{
protector = protector.CreateProtector(purpose);
}
var protectedData = Base64UrlTextEncoder.Decode(cookie);
byte[] userData = protector.Unprotect(protectedData);
var rawText = Encoding.UTF8.GetString(userData);
return rawText;
}
private string GetTlsTokenBinding(HttpContext context)
{
var binding = context.Features.Get<ITlsTokenBindingFeature>()?.GetProvidedTokenBindingId();
return binding == null ? null : Convert.ToBase64String(binding);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.