How to force the web app goes to user/logout when session expired?

Dondon510 261 Reputation points
2022-09-20T03:18:34.46+00:00

How to force the web app goes to user/logout when session expired?
my C# codes below only goes to /user/logout when the session was expired if the user triggering something (ie. click a menu or hit refresh)

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)  
.AddCookie(options =>  
{  
    options.LoginPath = "/User/Login";  
    options.AccessDeniedPath = "/User/Login";  
    options.LogoutPath = "/User/Logout";  
    options.SlidingExpiration = true;  
    options.ExpireTimeSpan = TimeSpan.FromMinutes(PrimeIoT.SIM.Models.AppSettings.Application.SESSION_TIMEOUT);  
});  
  
Developer technologies ASP.NET ASP.NET Core
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2022-09-20T10:16:04.64+00:00

    It's very simple. Create a JavaScript timer or use a meta tag that has the same timeout plus a second as the authentication cookie expiration. When the timer runs out, refresh the page.

    https://www.w3schools.com/tags/att_meta_http_equiv.asp
    https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Sreeju Nair 12,666 Reputation points
    2022-09-20T04:48:53.71+00:00

    Hi @Dondon510 , when the user gets logged out, your browser do not have any clue. One option you have is to use a Javascript timer that runs in the browser. The purpose of the timer is to issue a request and check whether the user is still logged in, you may use the response status code or see the cookie in the response. (Make sure you set SlidingExpiration to false).

    Now in the javascript timer method, when you detect the cookie expired, you can redirect the user to the login page.

    Hope this helps


  2. Dondon510 261 Reputation points
    2022-09-21T00:29:32.693+00:00

    BTW,

    still related to session timeout, is it possible to set no session timeout?, currently I set to long expiry timeout like 999999 but I thought there is a better way to disable the session timeout, please CMIIW


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.