在不使用IDataProtector的情况下加密 ASP.NET 核心中的cookie的简单/体面的方法是什么?



我正在尝试了解如何在 ASP.NET Core 2.1中加密cookie的内容。

如果我使用IDataProtector Protect方法来加密 cookie 的内容,我已经读到,如果网站移动到其他服务器、在服务器场、Azure 等中运行,Unprotect方法解密失败。 如果这是真的,并且我不想使用 Redis(或移动密钥(,并且能够使用简单的方法来加密内容,我将如何做到这一点?

这是我当前的代码(使用 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);
}

public void ConfigureServices(IServiceCollection services)

DirectoryInfo SharedKeysDataProtectionDirectory = new DirectoryInfo("shared/KeysDataProtection/Directory");
services.AddDataProtection()
.SetApplicationName("WebFarmSharedAppName")
.PersistKeysToFileSystem(SharedKeysDataProtectionDirectory);

最新更新