7

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?

1 Answer 1

6

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's not very helpful having the decryption code under Startup, as the point is to decrypt a cookie, which is not present during startup. Also, _storedOption is null, unless adding required configurations (e.g., passing ``CookieAuthenticationDefaults.AuthenticationScheme` to services.AddAuthentication). Plus, option => ... should be options => ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.