Skip to content

Instantly share code, notes, and snippets.

@gr1zix
Last active November 9, 2020 20:30
Show Gist options
  • Save gr1zix/ea9b658996c736b1b99ab7b833bedd0d to your computer and use it in GitHub Desktop.
Save gr1zix/ea9b658996c736b1b99ab7b833bedd0d to your computer and use it in GitHub Desktop.
Laravel 5.5 - 5.6 - The page has expired due to inactivity when login (auth)

Title I (Part 1): Laravel Quick Tip: Handling CsrfToken Expiration gracefully

or (check what working for you)

Title II (Part 2): “The page has expired due to inactivity” - Laravel 5.5 - 5.6

Part 1

Working but it must added to app/Exceptions/Handler.php not VerifyCsrfToken.php

Quick tip for handling CSRF Token Expiration - common issue is when you use csrf protection is that if a form sits there for a while (like a login form, but any the same) the csrf token in the form will expire & throw a strange error.

Handling it is simple, and is a good lesson for dealing with other types of errors in a custom manner.

In Middleware you will see a file VerifyCsrfToken.php and be tempted to handle things there. DON'T! Instead, look at your app/Exceptions/Handler.php, at the render($request, Exception $e) function.

All of your exceptions go through here, unless you have excluded them in the $dontReport array at the top of this file. You can see we have the $request and also the Exception that was thrown.

Take a quick look at the parent of VerifyCsrfToken - Illuminate\Foundation\Http\Middleware\VerifyCsrfToken. You can see from VerifyCsrfToken.php that handle() is the function called to do the token check. In the parent class, if the token fails, a TokenMismatchException is thrown.

So back in the Handler class, let's specifically handle that type of exception:

    public function render($request, Exception $e)
    {

        if ($e instanceof \Illuminate\Session\TokenMismatchException)
        {
            return redirect()
                    ->back()
                    ->withInput($request->except('password'))
                    ->with([
                        'message' => 'Validation Token was expired. Please try again',
                        'message-type' => 'danger']);
        }   

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

The code is simple - if the exception is a TokenMismatchException we will handle it just like a validation error in a controller. In our forms(s), we need to be sure to use the $request->old('field_name') (or the old('field_name') helper function) to repopulate. Simply going "back" will refresh the form with a new token so they can re-submit.

CAREFUL! - I found that using the http://laravelcollective.com/ Form::open() tag seemed to be incompatible with the token - redirect()->back() was not refresh the token for me. This may just be something in my code, but when I used a regular html tag it was fine. If this is happening to you, try that.

Part 2 (Working)

Working but it must added to app/Exceptions/Handler.php not VerifyCsrfToken.php

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.


Solution

Working for me

Add to app/Exceptions/Handler.php

// pull namespaces

  • use Exception;
  • use Illuminate\Session\TokenMismatchException;

// add body to render method or add render method if not exists inside your Kernel.php file

public function render($request, Exception $exception)
    {
        if ($exception instanceof TokenMismatchException) {

            return redirect()
                ->back()
                ->withInput($request->except('password', '_token'))
                ->with('error', 'Sorry, your session seems to have expired. Please login again.');

        }

        return parent::render($request, $exception);
    }
@joshmakar
Copy link

Thanks for sharing. This helped me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment