Reputation: 30063
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. 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?
Upvotes: 7
Views: 6933
Reputation: 15015
This is how you can decrypt a cookie based on CookieAuthenticationHandler
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);
}
}
Upvotes: 6