Web Niraj
  • Facebook
  • Flickr
  • Github
  • Linkedin
  • Twitter
  • YouTube
Online portfolio, code examples and developer blog
  • About
  • Contact
  • Portfolio
  • WordPress
Search the site...
  • Home
  • Blog
  • Laravel 5.x: Redirect CSRF Errors to Previous Page

Laravel 5.x: Redirect CSRF Errors to Previous Page

4

I have always found it frustrating that failing the CSRF check in Laravel 5.x throws an exception. I would rather prefer it redirect the user back to the previous page, and get them to try again. So, I modified the VerifyCsrfToken.php middleware to do just that, in just a few lines of code.

In the VerifyCsrfToken.php (found in folder App\Http\Middleware), I added the handle function that overwrites the default Laravel behaviour when the CSRF check fails. If this file doesn’t exist in your installation, the full code is included below:

On lines 22-29, I make sure unit tests, successful CSRF checks and pages that are excluded work as they should (this was taken from the original Illuminate\Foundation\Http\Middleware\VerifyCsrfToken class).

On line 32, instead of throwing the TokenMismatchException exception, I use the Redirect facade to redirect the user back to the previous page, and display an error.

Note: Remember to include the use statement for both the Closure and Redirect facades (see lines 5-6), or you will get exceptions when running your code.

Next time the CSRF check fails, your users will get a better looking error message and the chance to retry. Here is an example of how it looks on the login page:

Laravel-5.x-Custom-CSRF-Redirect

CSRF, Laravel 5, PHP, Tutorial

4 comments on “Laravel 5.x: Redirect CSRF Errors to Previous Page”

  1. DesignPond (@DesignPond) says:
    August 6, 2016 at 11:03 AM

    Nice one, Thank you! I wasn’t able to redirect from a TokenMismatchException, your script did the trick.

    Reply
  2. Dima says:
    August 11, 2016 at 4:43 PM

    Thans for help in this question!
    You have the error in your code.

    Must be “withErrors”:

    return Redirect::back()->withErrors(‘Sorry, we could not verify your request. Please try again.’);

    Reply
    • Niraj Shah says:
      September 12, 2016 at 3:28 PM

      Thanks for pointing that out. The correct code is actually:

      return Redirect::back()->withErrors( ['Sorry, we could not verify your request. Please try again.'] );

      Reply
  3. adaza90 says:
    February 11, 2018 at 7:30 PM


    public function handle($request, Closure $next)
    {
    if (
    $this->isReading($request) ||
    $this->runningUnitTests() ||
    $this->inExceptArray($request) ||
    $this->tokensMatch($request)
    ) {
    return $this->addCookieToResponse($request, $next($request));
    }

    // redirect the user back to the last page and show error
    return Redirect::back()->withErrors( trans('auth.token_failed') );
    }

    new code 2018

    Reply

Leave a ReplyCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

StackExchange / StackOverflow

profile for Niraj Shah on Stack Exchange, a network of free, community-driven Q&A sites

Support Me

Buy Me a Coffee

PSN Profile

Tags

ACL Amazon Web Services Android Android 4.4 KitKat Android 5.0 Lollipop Apache Backup Bash Bug Command Line Cordova cPanel / WHM Facebook Facebook Graph API Facebook PHP SDK 4.0 Facebook Social Plugins Fan Page Flash Geolocation Google Nexus 5 Hacking HTML5 Input Sanitization iOS JavaScript jQuery Laravel 5 Laravel 5.2 Linux Mac OS NodeJS Parse PDF PHP Plugin Portfolio Review Security Server SSH SSL Sysadmin Tutorial WordPress WordPress Plugins
© 2011-2025 Niraj Shah
  • Blog
  • Portfolio
  • WordPress
  • About Me
  • Contact Me
  • Privacy Policy
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Privacy Policy