RidRoid
RidRoid

Reputation: 961

Disable Csrf for ajax query

I'm using Laravel 5.1 and i'm tryin to disable csrf validation for this route to be able to perform some remote validations using Jquery Form Validator :

Route::post('verify', 'formController@check');

As mentioned in the documentation, I just have to add my URI to the $excludeproperty. whice I did :

namespace App\Http\Middleware;

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 = [
    'verify',
];
}

That did not work, So I tried to disable csrf validation for the whole application :

class Kernel extends HttpKernel
{
protected $middleware = [
    ...
    //\App\Http\Middleware\VerifyCsrfToken::class,
];
protected $routeMiddleware = [
    ...
];
}

That did not work either. I keep getting this error on the console :

POST http://domain.name/verify 500 (Internal Server Error)

whice exactly points to this line(The validator's js file):

ajax({url:b,type:"POST",cache:!1,data:g,dataType:"json",error:function(a){return h({valid:!1,message:"Connection failed with status: "+a.statusText},f),!1}

What am I missing? thanks for your help.

Upvotes: 0

Views: 1476

Answers (2)

RidRoid
RidRoid

Reputation: 961

Solved the problem.

For Laravel 5 and above, adding protected $except = ['verify',]; to App\Http\Middleware\VerifyCsrfToken.php does solve the problem.

NB : Google's inspect tool (Network menu) helped me understand what was really happening.

Upvotes: 1

Ankur Mishra
Ankur Mishra

Reputation: 111

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier {

protected $except_urls = [
    'verify'
];

public function handle($request, Closure $next)
{
    $regex = '#' . implode('|', $this->except_urls) . '#';

    if ($this->isReading($request) || $this->tokensMatch($request) || preg_match($regex, $request->path()))
    {
        return $this->addCookieToResponse($request, $next($request));
    }

    throw new TokenMismatchException;
}

}

Upvotes: 1

Related Questions