Reputation: 475
I have this in Laravel 4.2 Route::when('*', 'csrf', ['post']);
that insert csrf verification to all post, how can I port to Larevel 5.2 ?
This is my own csrf, without using default provide by Laravel:
<?php
namespace App\Http\Middleware;
use Closure;
use Input;
class VerifyCsrfToken1
{
public function handle($request, Closure $next)
{
$token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
if ($request->session()->token() === $token) {
return $next($request);
}
throw new TokenMismatchException;
}
}
I created my personal csrf middleware, but I don't know how to attach them on ALL post request
I want to attach it to all post via Route
's facade. (file routes.php)
Thanks :)
Upvotes: 2
Views: 228
Reputation: 28959
Laravel 5 wires up middleware a bit differently, you won't be doing this through the Request
facade.
You want to first register your Middleware as global. Open up app/Http/Kernel.php
and add it to the global $middleware
array.
protected $middleware = [
VerifyCsrfToken1::class
...
Then in your middleware class, check to see if it is handling a POST request. If not, have it just pass the request along without doing anything.
if($request->method() != "POST") {
// Move right along
return $next($request);
}
Side note: As you noted Laravel has a VerifyCsrfToken
middleware baked in already. I'd advise trying to adapt this if possible.
Upvotes: 2