7

The Error

Enter image description here

My Scenario

Firstly I know that this error message is a CSRF / session error message and that's fine; in fact it's behaving as expected. For reasons specific to my application I've made it so that to access an account I send a post request and build out the page depending on that response data.

The problem is that when the session times out on that page, my application does nothing, but throw this error message. I then physically have to type in a URL to get redirected to the login page which is not ideal for clients.

My Question

How do I control the behaviour of my application so I can modify what happens when this CSRF error occurs, for example if I wanted to make a custom page or use a controller to perform a redirect, etc.?

The difference is that I know what this error is. I want a way to redirect while this error is present, I'm not trying to stop the error from showing, and I'm trying to redirect from it. In my case it's not an error; it's a behaviour that I expect!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kenziiee Flavius
  • 1,918
  • 4
  • 25
  • 57
  • 2
    Possible duplicate of ["The page has expired due to inactivity" - Laravel 5.5](https://stackoverflow.com/questions/46141705/the-page-has-expired-due-to-inactivity-laravel-5-5) – Rahman Qaiser Mar 22 '18 at 07:29
  • 2
    @RahmanQaiser if you read the question you would see that its not at all a duplicate... – Kenziiee Flavius Mar 22 '18 at 07:30
  • @KenziieeFlavius Not sure which version of Laravel are you using. In 5.4, if I remember it correct, there is a handler.php file['/app/Exceptions/Handler.php']. You can edit it. – harry Mar 22 '18 at 07:56
  • @harry thanks ill check it out – Kenziiee Flavius Mar 22 '18 at 07:58

1 Answers1

11

In your app/Exceptions/Handler.php in render function add the lines:

    if ($e instanceof \Illuminate\Session\TokenMismatchException) {

        return redirect('/login')->with('message', 'Sorry, your session seems to have expired. Please login again.');

   }

before the line :

return parent::render($request, $e);

This should redirect to login on a Token mismatch.

Link with further explanation: https://gist.github.com/jrmadsen67/bd0f9ad0ef1ed6bb594e

Kenziiee Flavius
  • 1,918
  • 4
  • 25
  • 57
Mehravish Temkar
  • 4,275
  • 3
  • 25
  • 44