我想手动解密ASP.NET Core 3.0.0存储的.AspNetCore.Identity.Application
cookie,以查看其中包含的信息。我知道微软已经在ASP.NET Core 2.2和 3.0之间相当大地改变了这个过程,所以现在3.0已经发布到普通可用性,我想知道:如何在我的应用程序代码中手动解密这个cookie?
我想手动解密ASP.NET Core 3.0.0存储的.AspNetCore.Identity.Application
cookie,以查看其中包含的信息。我知道微软已经在ASP.NET Core 2.2和 3.0之间相当大地改变了这个过程,所以现在3.0已经发布到普通可用性,我想知道:如何在我的应用程序代码中手动解密这个cookie?
这就是如何根据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);
}
}