I am trying to understand how to encrypt contents of cookies in ASP.NET Core 2.1.
If I am using the IDataProtector Protect method to encrypt contents of a cookie, I have read that the Unprotect method will fail decryption if website is moved to a different server, running in a server farm, Azure, etc.
If that is true and I don't want to use Redis (or moving keys around), and be able to use a simple method to encrypt contents how would I go about this?
This is my current code (using the IDataProtector):
public static void SetEncryptedCookie()
{
var cookieData = new Dictionary<string, string>()
{
{ "a", "123" },
{ "b", "xyz" },
{ "c", DateTime.Now.ToString() },
{ "UserID", "unique-number-789" }
};
CookieOptions options = new CookieOptions
{
Expires = DateTime.Now.AddDays(90)
,HttpOnly = true
,Secure = true
,IsEssential = true // GDPR
,Domain = ".example.org"
};
// _dataProtector = provider.CreateProtector("somepurpose");
string protectedCookie = _dataProtector.Protect(cookieData);
// IHttpContextAccessor _accessor
// write cookie to http response
_accessor.HttpContext.Response.Cookies.Append("mycookie", protectedCookie, options);
// retrieve encrypted cookie contents.
// ##### this will fail in server farms.
var cookieEnc = _accessor.HttpContext.Request.Cookies["mycookie"];
var cookieDec = _dataProtector.Unprotect(cookieEnc);
}