Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel catch TokenMismatchException

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);
    }
}

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


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.');
    }
}

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();
  }
}

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.
            }
        });
    }

}

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.');
    }
  });