Home > front end >  How do I automatically redirect when the session cookie expires?
How do I automatically redirect when the session cookie expires?

Time:02-11

When a user is idle for ten minutes, I would like to have an automatic redirect. Below is the test code, which is not working.

The LoginPath, LogoutPath, and AccessDeniedPath do not exist. Therefore, I would expect an error after the timeout period. Instead, I can continue to successfully click "Home" and "About" without an error and without being redirected. My expectation is that I will be redirected back to the home page.

Sample code:

services.AddMemoryCache();
services.AddSession(options =>
    {
        options.Cookie.Name = "MyAppCookie";
        options.Cookie.IsEssential = true;
        options.Cookie.HttpOnly = true;
        options.IdleTimeout = TimeSpan.FromMinutes(1);
    });

           
services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Login";
        options.AccessDeniedPath = "/Account/AccessDenied";
        options.SlidingExpiration = true;
    });

CodePudding user response:

On the server side, your code can know about the session timeout. Using it, you can set a cookie indicating when the actual session timeout occurred (no mention of whether it was an active session timeout or an idle timeout). The javascript running on the page can periodically read the cookie and redirect the user when the timeout value is exceeded.

This is one of many methods that I hope will help you.

Refer this post :

In ASP Net Core 3.1 Expiration cookie is not redirecting to login page when using ajax

CodePudding user response:

You can use Axios interceptors for them, in the first request after token expiration you can redirect it. Also, you can decode your token at [https://jwt.io/][1] and take the expiration date, you can check by it.

  • Related