ASP.Net Core Cookie身份验证不是持久性的 [英] ASP.Net Core Cookie Authentication is not persistant

查看:97
本文介绍了ASP.Net Core Cookie身份验证不是持久性的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用 ASP.Net Core 2.2 开发网站.我正在通过自定义Cookie身份验证(而非身份)实现登录/注销.

I started developing websites using ASP.Net Core 2.2. I'm implementing login/logout by a custom cookie authentication (not Identity).

请查看或克隆回购:

git clone https://github.com/mrmowji/aspcore-custom-cookie-authentication.git .

...或阅读以下代码段.

... or read the following code snippets.

这是 Startup.cs 中的代码:

public void ConfigureServices(IServiceCollection services) {
  ...

  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => {
      options.LoginPath = new PathString("/login");
      options.ExpireTimeSpan = TimeSpan.FromDays(30);
      options.Cookie.Expiration = TimeSpan.FromDays(30);
      options.SlidingExpiration = true;
    });

  ...

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
  ...

  app.UseHttpsRedirection();
  app.UseStaticFiles();
  app.UseCookiePolicy();

  app.UseAuthentication();

  app.UseMvc(routes =>
  {
    ...

这是 Login 操作的代码:

public async Task<IActionResult> Login(LoginViewModel userToLogin) {
  var username = "username"; // just to test
  var password = "password"; // just to test
  if (userToLogin.UserName == username && userToLogin.Password == password) {
    var claims = new List<Claim> {
      new Claim(ClaimTypes.Name, "admin"),
      new Claim(ClaimTypes.Role, "Administrator"),
    };

  var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme);

  var authProperties = new AuthenticationProperties {
    AllowRefresh = true,
    ExpiresUtc = DateTimeOffset.UtcNow.AddDays(10),
    IsPersistent = true,
  };

  await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

    ...

Cookie已按预期设置.我有一个 .AspNetCore.Cookies cookie,其有效期为10天.但是大约30分钟后,用户将注销.即使浏览器关闭后,如何强制经过身份验证的用户保持登录状态?

Cookies are set as expected. I have a .AspNetCore.Cookies cookie with expiration date of 10 days later. But after about 30 minutes, the user is logged out. How to force the authenticated user to stay logged in, even after the browser is closed?

推荐答案

感谢 @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.

这篇关于ASP.Net Core Cookie身份验证不是持久性的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆