我正在尝试了解如何在 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);