如何正确延长Cookie的有效期?用户在不到一个小时的时间内被自动踢了

时间:2018-08-02 16:06:41

标签: c# cookies asp.net-core

我正在使用Cookie将经过身份验证的用户保留在我的页面上

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc(config =>
  {
    var policy = new AuthorizationPolicyBuilder()
                   .RequireAuthenticatedUser()
                   .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
  });

  services.AddAuthentication(options =>
  {
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  app.UseCookieAuthentication(new CookieAuthenticationOptions()
  {
    AccessDeniedPath = "/Accounts/Forbidden/",
    AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    LoginPath = "/Account/Login/",
    LogoutPath = "/Account/Login/",
    ExpiresTimeSpan = TimeSpan.FromDays(10)
  });
}

AccountController.cs

public async Task<IActionController> Login(UserVm model)
{
  if(_repo.ValidateCredentials(model.UserName, model.Password))
  {
    var user = _repo.FindUser(model.UserName);
    AuthenticationProperties props = null;
    if(model.RememberLogin)
    {
      props = new AuthenticationProperties
      {
        IsPersistent = true,
        ExpiresUtc = DataTimeOffset.UtcNow.Add(TimeSpan.FromDays(10))
      };
    }

    ClaimsIdentity identity = new ClaimsIdentity(GetUserClaims(user), CookieAuthenticationDefaults.AuthenticationScheme);
    ClaimsPrincipal principal = new ClaimsPrincipal(identity);

    await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props);

    return Redirect("~/");
  }
}

它说here,如果启用IsPersistent,它将覆盖ExpireTimeSpan上的CookieAuthenticationOptions。我想将Cookie延长至10天。但是似乎我的用户在不到一个小时的时间内就被自动踢了出去。我在IIS上实时发布应用程序时注意到了这一点。这与我的服务器有关吗?

如何正确延长Cookie的有效期,以免用户被踢出?我正在使用netcoreapp1.1

0 个答案:

没有答案