不使用IDataProtector加密ASP.NET Core中的cookie的简单/体面的方法是什么?

时间:2018-09-18 22:54:43

标签: c# encryption asp.net-core

我试图了解如何在ASP.NET Core 2.1中加密Cookie的内容。

如果我正在使用IDataProtector Protect方法对Cookie的内容进行加密,那么我已经读到,如果将网站移至运行在服务器场中的其他服务器,则Unprotect方法将无法解密。 Azure等 如果是这样,并且我不想使用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);
    }

1 个答案:

答案 0 :(得分:0)

public void ConfigureServices(IServiceCollection services)

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