且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.Net Core Cookie身份验证不是持久性的

更新时间:2023-12-05 23:46:22

感谢 @LeonardoSeccia 答案.请阅读有关主要问题的评论.

Thanks to @LeonardoSeccia I could find the answer. Please read the comments on the main question.

我只需要添加 ConfigureServices 方法中的>数据保护服务,并提供一种在某些地方存储/持久存储密钥(用于加密/解密敏感数据)的方法,否则在服务器或应用程序池重新启动时,则会生成新密钥,并且旧的加密数据(包括身份验证Cookie)将无法按照其必须的方式解密,从而导致身份验证失败.如果要部署到像我这样的共享主机,则很有必要.

I just needed to add data protection service inside ConfigureServices method and provide a way to store/persist the keys (which are used to encrypt/decrypt sensitive data) somewhere, otherwise whenever the server or the app pool restarts, new keys would be generated and old encrypted data (including authentication cookies) will not get decrypted the way they must, which results in a failed authentication. It's necessary if you're deploying to a shared host like me.

如果您以前使用过.NET Framework中的ASP.Net,则此数据保护概念在某种程度上等效于 MachineKey .

If you've used ASP.Net from .Net Framework before, this Data Protection concept is somehow equivalent to MachineKey.

我已经决定使用文件存储密钥.这是 Startup.cs 中的最终更改:

I've decided to use a file to store the keys. Here is the final changes in Startup.cs:

public Startup(IConfiguration configuration, IHostingEnvironment environment) {
  Configuration = configuration;
  hostingEnvironment = environment;
}

private IHostingEnvironment hostingEnvironment;

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
  // create a directory for keys if it doesn't exist
  // it'll be created in the root, beside the wwwroot directory
  var keysDirectoryName = "Keys";
  var keysDirectoryPath = Path.Combine(hostingEnvironment.ContentRootPath, keysDirectoryName);
  if (!Directory.Exists(keysDirectoryPath)) {
    Directory.CreateDirectory(keysDirectoryPath);
  }
  services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(keysDirectoryPath))
    .SetApplicationName("CustomCookieAuthentication");

  services.Configure<CookiePolicyOptions>(options =>
  {
  ...

如果您想要整个源代码,请回购.

Please check the repo out if you want the whole source code.