asafg8 asafg8 - 1 month ago 8
PHP Question

TokenMismatchException , despite excluding route

Im trying to create an img upload using ajax .
Im using the plugin https://github.com/Vinelab/mr-uploader ,and i'm getting CSRFTokenMismatchException .
Iv'e solved the issue before by adding the route to $execpet on verifyCsrf

class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'/admin/upload'
];

}


Since solving the problem the first time i've reveted the whole project back to laravel 5 from laravel 5.1 (long story , i've had to do it )
now the problem appears agian .
when trying to send a post request to that route i get 'TokenMismatchException'.

Answer

Method 1: Disable CSRF Protection

Add the following code in VerifyCsrfToken.php

This route will ignored from checking csrf token..

public function handle($request, Closure $next)
    {
        //disable CSRF check on following routes
        $skip = array(
                    '/admin/upload',
                    );

        foreach ($skip as $key => $route) {
            //skip csrf check on route
            if($request->is($route)){
                return parent::addCookieToResponse($request, $next($request));
            }
        }
        return parent::handle($request, $next);
    }

Method 2: Add CSRF TOKEN in ajax request

var token      = "{{ csrf_token() }}";

    $.ajax({
         type : "POST",
         url  : "/admin/upload",
         data : {_token:token},


 });
Comments