共享服务器上 PersistKeysToFileSystem 的文件路径

File Path for PersistKeysToFileSystem on shared server

我正在尝试让登录的用户保留我的密钥。由于我目前正在为网站使用共享主机,所以我决定使用文件系统来存储密钥环。所以代码看起来像这样:

services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(""))
.SetApplicationName("MyWebsite")
.SetDefaultKeyLifetime(TimeSpan.FromDays(90))
.ProtectKeysWithCertificate(cert);

但是,我不太了解的是我应该把这些密钥放在哪里,以及我通过什么路径才能让它们在那里。由于这是一个 MVC 核心应用程序,我有点困惑,在 MVC 5 中我会把它放在 App_Data 文件夹中,但这里没有 App_Data 文件夹,我想确保它保持安全并且无法通过浏览器访问。

另一件事是我传递给它的是相对路径还是直接路径?如果是相对的,我的出发点在哪里?是bin、根目录还是别的?

最简单的方法可能是在应用程序文件夹中创建一个文件夹。例如,创建一个名为 Keys 的文件夹,并使用 IHostingEnvironment 对象获取 app 文件夹。像这样:

public class Startup
{
    private readonly IHostingEnvironment _environment;

    public Startup(IHostingEnvironment environment)
    {
        _environment = environment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var keysFolder = Path.Combine(_environment.ContentRootPath, "Keys");

        services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(keysFolder))
            .SetApplicationName("MyWebsite")
            .SetDefaultKeyLifetime(TimeSpan.FromDays(90))
            .ProtectKeysWithCertificate(cert);
    }

    // snip
}