Search code examples
phplaravelexceptioncsrflaravel-5

Laravel catch TokenMismatchException


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?


Solution

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