我想了解如何在 ASP.NET Core 2.1 中加密 cookie 的内容。
如果我使用 IDataProtector Protect
方法来加密 cookie 的内容,我已经了解到如果网站移动到不同的服务器,Unprotect
方法将无法解密,在服务器场、Azure 等中运行
如果这是真的,并且我不想使用 Redis(或四处移动 key ),并且能够使用一种简单的方法来加密内容,我将如何处理这个问题?
这是我当前的代码(使用 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);
关于c# - 在不使用 IDataProtector 的情况下,在 ASP.NET Core 中加密 cookie 的简单/体面的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52395650/