55

Can the TokenMismatchException be catched using try catch block? Instead of displaying the debug page that shows the "TokenMismatchException in VerifyCsrfToken.php line 46...", I want it to display the actual page and just display an error message.

I have no problems with the CSRF, I just want it to still display the page instead of the debug page.

To replicate (using firefox): Steps:

  1. Open page (http://example.com/login)
  2. Clear Cookies (Domain, Path, Session). I am using web developer toolbar plugin here.
  3. Submit form.

Actual Results: "Whoops, looks like something went wrong" page displays. Expected Results: Still display the login page then pass an error of "Token mismatch" or something.

Notice that when I cleared the cookies, I didn't refresh the page in order for the token to generate a new key and force it to error out.

UPDATE (ADDED FORM):

        <form class="form-horizontal" action="<?php echo route($formActionStoreUrl); ?>" method="post">
        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
        <div class="form-group">
            <label for="txtCode" class="col-sm-1 control-label">Code</label>
            <div class="col-sm-11">
                <input type="text" name="txtCode" id="txtCode" class="form-control" placeholder="Code" />
            </div>
        </div>
        <div class="form-group">
            <label for="txtDesc" class="col-sm-1 control-label">Description</label>
            <div class="col-sm-11">
                <input type="text" name="txtDesc" id="txtDesc" class="form-control" placeholder="Description" />
            </div>
        </div>
        <div class="form-group">
            <label for="cbxInactive" class="col-sm-1 control-label">Inactive</label>
            <div class="col-sm-11">
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="cbxInactive" id="cbxInactive" value="inactive" />&nbsp;
                        <span class="check"></span>
                    </label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-12">
                <button type="submit" class="btn btn-primary pull-right"><i class="fa fa-save fa-lg"></i> Save</button>
            </div>
        </div>
    </form>

Nothing really fancy here. Just an ordinary form. Like what I've said, the form is WORKING perfectly fine. It is just when I stated the above steps, it errors out due to the TOKEN being expired. My question is that, should the form behave that way? I mean, when ever I clear cookies and session I need to reload the page too? Is that how CSRF works here?

4
  • what form? this page is a blank example Commented Mar 18, 2015 at 6:10
  • Post the code of your form, we need to see what is wrong there.
    – sybear
    Commented Mar 18, 2015 at 6:12
  • And your routes as well.
    – sybear
    Commented Mar 18, 2015 at 6:18
  • Any reason not to add a meta refresh for 2 hours or whatever the expires time is?
    – Justin
    Commented Feb 25, 2016 at 15:38

7 Answers 7

101

You can handle TokenMismatchException Exception in App\Exceptions\Handler.php

<?php namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Session\TokenMismatchException;


class Handler extends ExceptionHandler {


    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        'Symfony\Component\HttpKernel\Exception\HttpException'
    ];
    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }
    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof TokenMismatchException){
            // Redirect to a form. Here is an example of how I handle mine
            return redirect($request->fullUrl())->with('csrf_error',"Oops! Seems you couldn't submit form for a long time. Please try again.");
        }

        return parent::render($request, $e);
    }
}
5
  • 13
    For future readers: don't forget to add the use declaration at the top, otherwise $e instanceof TokenMismatchException is false. Commented Dec 7, 2015 at 17:16
  • Have you successfully tested that this handles the Exception? I can't get this to work
    – simonhamp
    Commented Dec 16, 2015 at 11:14
  • 4
    You can show this error message in the blade using @if (session('csrf_error')) {{ session('csrf_error') }} @endif
    – Eranda
    Commented Sep 23, 2016 at 5:31
  • 3
    This example works in Laravel 5.3, I would recomment using ->withErrors('Oops ....') and maybe doing redirect()->back()->withErrors instead.
    – WoodyDRN
    Commented Feb 1, 2017 at 19:15
  • will this give a proper response on ajax request? Commented Jan 12, 2018 at 11:29
17

A Better Laravel 5 Solution

in App\Exceptions\Handler.php
Return the user to the form with a new valid CSRF token, so they can just resubmit the form without filling the form again.

public function render($request, Exception $e)
    {
         if($e instanceof \Illuminate\Session\TokenMismatchException){
              return redirect()
                  ->back()
                  ->withInput($request->except('_token'))
                  ->withMessage('Your explanation message depending on how much you want to dumb it down, lol!');
        }
        return parent::render($request, $e);
    }

I also really like this idea:

https://github.com/GeneaLabs/laravel-caffeine

2
  • I use my own variation of the caffeine concept and it seems to fail. I'm not sure why, but I suspect something odd like maybe the tab is in the background so javascript is paused and it never refreshes the token or something. Or they put their computer to sleep by closing the laptop lid. So clean handling of a bad token should hopefully be better than trying to keep the token refreshed. At least in my case. Commented Mar 13, 2017 at 18:56
  • how to access the returned input data sent by withInput() in Laravel 5.4.24? Commented Jul 10, 2017 at 12:44
12

Instead of trying to catch the exception just redirect the user back to the same page and make him/her repeat the action again.

Use this code in the App\Http\Middleware\VerifyCsrfToken.php

<?php
namespace App\Http\Middleware;
use Closure;
use Redirect;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];

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

        // redirect the user back to the last page and show error
        return Redirect::back()->withError('Sorry, we could not verify your request. Please try again.');
    }
}
1
  • 6
    This answer is out of date for 5.4- $this->shouldPassThrough($request) is now $this->inExceptArray($request)
    – Brendan
    Commented May 2, 2017 at 5:11
5

Laravel 8 seems to handle exceptions a little differently and none of the solutions above worked in my fresh install of Laravel. So I'm posting what I ended up getting to work and hoping it can be helpful to someone else. See Laravel Docs here.

Here's my App\Exceptions\Handler.php file:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (\Symfony\Component\HttpKernel\Exception\HttpException $e, $request) {
            if ($e->getStatusCode() == 419) {
                // Do whatever you need to do here.
            }
        });
    }

}
2
  • 1
    Works like a charm. Thank you. I've been trying to do this on TokenMismatchException directly, but no dice.
    – noviolence
    Commented Dec 8, 2020 at 17:32
  • @noviolence I also have tried TokenMismatchException but somehow it didn't work. So, this one is the best solution so far for Laravel 8
    – Abaij
    Commented Mar 3 at 2:07
4

Laravel 5.2: Modify App\Exceptions\Handler.php like this:

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Illuminate\Session\TokenMismatchException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof TokenMismatchException) {
            abort(400); /* bad request */
        }
        return parent::render($request, $e);
    }
}

In AJAX requests you can respond to the client using abort() function and then handle the response in client side using AJAX jqXHR.status very easily, for example by showing a message and refreshing the page. Don't forget to catch the HTML status code in jQuery ajaxComplete event:

$(document).ajaxComplete(function(event, xhr, settings) {
  switch (xhr.status) {
    case 400:
      status_write('Bad Response!!!', 'error');
      location.reload();
  }
}
1
  • 1
    Nice AJAX considerations, why not pass a message too? abort('400', 'YOUR FORM HAS EXPIRED!');
    – Harry Bosh
    Commented Aug 24, 2016 at 2:15
2

Nice one. Laravel 8 definitely does it in a different way. The block of code below doesn't work with laravel 8.

  if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
    return redirect()->route('login');
  }

But this one does:

  $this->renderable(function (\Symfony\Component\HttpKernel\Exception\HttpException $e, $request) {
    if ($e->getStatusCode() == 419) {
      return redirect('/login')->with('error','Your session expired due to inactivity. Please login again.');
    }
  });
 
0

This is the only thing I could get working to to pass the message to a page displaying validation errors in Laravel 9.

// Inside app/Exceptions/Handler
$this->renderable(function (Exception $exception) {
    if ($exception instanceof HttpException) { 
        if ($status === 419) {
            return back()
            ->withErrors(['field' => 'Session expired for security reasons. Try again.'])
            ->withInput($request->except('_token'));
        }
    }
});

Note the field key, which should match the key on the validation errors bag for the Blade view you're redirecting to. For example:

@error("field")
  <div>
   <p class="text-red-500"> {{ $message }} </p>
  </div>
@enderror

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.