Home > Back-end >  redirect to the login page after session expired
redirect to the login page after session expired

Time:06-18

In Laravel, after the user stays inactive for x minutes, the session expires and it logs out. However, he can still be in the app until he refreshes the page or goes to another route.

Is there any way to redirect him automatically to the login page after the session expires, without needing to refresh the page?

As far as I know, I have to do it with an Ajax request, but I am not sure how. This is what I found after searching for a while:

$.ajax({
  url:url,
  type:"POST",  // or get
  data:parameters,
  error: function(xhr, type, error){
          window.location.replace("/login");
     }
});

CodePudding user response:

You could start a timeout when a user lands on the page with the session lifetime, and make a request to check if user is still logged in

// 4 hours
let sessionLifetime = 4 * 60 * 60;
setTimeout(() => {
   // an authenticated endpoint, could be anything, if request fail, then user is not logged in anymore
   axios.get('/me').catch(e => {
       window.location.replace("/login");
   })
}, sessionLifetime * 1000);

The only downside is that by making a request you are refreshing the session, so if the request pass, you just need to restart your timeout :


// 4 hours
let sessionLifetime = 4 * 60 * 60;

let isAuth = () => {
   // an authenticated endpoint, could be anything, if request fail, then 
    user is not logged in anymore
    axios.get('/me').then(() => {
       setTimeout(isAuth, sessionLifetime * 1000)
    }).catch(e => {
       window.location.replace("/login");
    })
}

setTimeout(isAuth, sessionLifetime * 1000)

you could make an endpoint dedicated to that check instead of using a random one. i used axios here, but it's the same principle with jquery $.ajax

Another solution would be to assume that the user is not logged in anymore when the timeout is executed, without checking with a request, but that's more risky, because the user could have another tab open

  • Related