ASP Net Core 3.1会话永不过期

时间:2020-08-28 08:58:45

标签: asp.net-core asp.net-core-3.1

我已经尝试了在StackOverflow上找到的所有内容,但是仍然无法管理Session(内容)自动过期。

我尝试过:

我不访问ajax调用中的会话数据(设置,获取),因此这不会自动增加会话过期时间。

在旧的AspNet MVC中,它是如此简单/琐碎-立即按预期工作。

然后我所做的一切:我将自定义登录名(数据)存储到Session中,并期望Session在用户闲置20分钟后消失。但这永远不会发生。

有什么想法吗?

编辑:Cookies

 lb_commonator=ffffffff0972280045525d5f4f58455e445a4a423660; crowd.token_key=7qN9z4UYR3tCjYdronwmOw00; .AspNetCore.Antiforgery.tYkxYH7Bg6I=CfDJ8OahW8JbNMdPv78xOmnUC6BtivuFvWy4RhYaN0oRtiUvkLpVtHLxgQaQOS1RTNqT8E0LaobeaNdLIhhoy4z4qSJleqiK2QJTWEptEDFAITNCTdh03AIqcd0mBL0FZeFcr5GalTfqiNahST7eUL7Wnpg; .AspNetCore.Session=CfDJ8OahW8JbNMdPv78xOmnUC6Cwi2HZVPs93%2Bohf8c%2BvQ1hWZVHeu54cwkg8PND41KXN1F%2BeAOSnTnkiT3RAGb3mPQjLRMpcq1x9f5KFrgegRRoEDHx%2FgEknhSOo8yCfKp1srlrzTWUtpUF8tsFKn1JwPLI9fHT77SGscSkTMrsueYr

编辑2(IdleTimeout和ExpireTimeSpan完全无效):

    // Add session
    // Add session
    // Add session
    services.AddSession();

    // TESTING: TODO:
    // TESTING: TODO:
    // TESTING: TODO:
    //services.AddSession(options =>
    //{
    //    options.IdleTimeout = TimeSpan.FromSeconds(10);
    //});
    //services.ConfigureApplicationCookie(options =>
    // {
    //     options.SlidingExpiration = true;
    //     options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
    // });

编辑3:

enter image description here

1 个答案:

答案 0 :(得分:0)

// TESTING: TODO:
// TESTING: TODO:
// TESTING: TODO:
//services.AddSession(options =>
//{
//    // session data experation in storage
//    // for example, if you use redis, this will add ttl 10 secs
//    // for data in redis, but no influence to cookie lifitime
//    options.IdleTimeout = TimeSpan.FromSeconds(10);
//    // this will affect on cookie liftime in browser
//    // if you do not set it, cookie will be Session
//    // and expire when you close your browser
//    options.Cookie.MaxAge = TimeSpan.FromHours(1);
//});

enter image description here

编辑:

  1. 要刷新现有的会话cookie,您将需要跟踪cookie创建时间(例如,在会话数据中)并在中间件中重置cookie

         app.Use(async (context, next) =>
         {
             string sessionCookie;
             if (/*add here expiration check &&*/ context.Request.Cookies.TryGetValue("SessionCookieName", out sessionCookie))
             {
                 context.Response.Cookies.Append("SessionCookieName", sessionCookie, new CookieOptions
                 {
                     MaxAge = TimeSpan.FromSeconds(10),
                     HttpOnly = true,
                     SameSite = SameSiteMode.Lax,
                     Path = "/"
                 });
             }
             await next.Invoke();
         });
    
  2. 或者您也可以编写用于处理会话cookie滑动过期(可能将过期时间添加到cookie数据中)的中间件,而不是默认的会话中间件。默认实现为here

  3. 我不知道您要解决什么样的任务,但我认为以下配置已足够:

     services.AddSession(options =>
     {
        options.IdleTimeout = TimeSpan.FromSeconds(10);
     });
    

它将在10秒钟内使您的会话数据失效(cookie可能仍处于活动状态),并提供会话数据的到期日。