'Decrypt ".AspNetCore.Session" cookie in ASP.NET Core

In Asp.Net core, a cookie is created when you configure your app to app.UseSession(). By default the cookie is called ".AspNetCore.Session". Its value identifies the session to be used. Currently, I'm saving my session data on a sql server. I need to know the decrypted value of ".AspNetCore.Session" so that I can lookup the session in the database.

Is there a way to decrypt this value? I know ASP.NET must do it behind the scenes somehow.



Solution 1:[1]

I had to extract the private Pad function from Microsoft.AspNetCore.Session, but I was able to get what I needed:

public class DiscussionController : Controller
{   
    private readonly IDataProtector _dataProtector;        

    public DiscussionController(IDataProtectionProvider dataProtectionProvider)
    {
        var protectorPurpose = "whatever purpose you want";

        _dataProtector = dataProtectionProvider.CreateProtector(protectorPurpose);
    }

    public IActionResult Index()
    {     
       HttpContext.Request.Cookies.TryGetValue(".AspNetCore.Session", out string cookieValue);

       var protectedData = Convert.FromBase64String(Pad(cookieValue));

       var unprotectedData = _dataProtector.Unprotect(protectedData);

       var humanReadableData = System.Text.Encoding.UTF8.GetString(unprotectedData);

        return Ok();
    }

    private string Pad(string text)
    {
        var padding = 3 - ((text.Length + 3) % 4);
        if (padding == 0)
        {
            return text;
        }
        return text + new string('=', padding);
    }    
}

The Pad function was taken from: https://github.com/aspnet/AspNetCore/blob/87629bbad906e9507026692904b6bcb5021cdd33/src/Middleware/Session/src/CookieProtection.cs#L61-L69

Solution 2:[2]

The session source has everything, but you should need to know it, ISessionStore and IDistributedSessionStore gives you a sessionkey to use.

Rather than make an assumption about the cookie format, what is stopping you from using the store APIs?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 blowdart