I think the easiest way is to create your own CSRF Middleware to manage exclusions.
Nov 23, 2014
19
Level 7
[L5] Disable CSRF Middleware on certain routes
Hi all,
I have found plenty of solutions on how to rip the CSRF Middleware out of L5 alltogether... but what im wondering is if there would be an option to just exclude certain routes from the CSRF Middleware.
Anyone any ideas?
Thanks!
Level 52
One way is to extend the VerifyCsrfToken and have an array of no csrf urls inside :
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Session\TokenMismatchException;
class VerifyCsrfToken extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken {
protected $except_urls = [
'contact/create',
'contact/update',
...
];
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;
}
}
And change in Kernel to point the new middleware :
protected $middleware = [
...
'App\Http\Middleware\VerifyCsrfToken',
];
11 likes
Please or to participate in this conversation.