If you haven't changed your Http\Kernel.php stack, the VerifyCsrfToken middleware is going to be called every time you make a non-GET request. So, unless you are explicitly setting a _token parameter on your request, you will receive a TokenMismatchException. It looks like your middleware is acting in addition to the standard VerifyCsrfToken middleware check.
Creating an Ajax CSRF Middleware
I'm attempting to create a Middleware based on the existing CSRF Middleware (I'm trying to avoid touching files that still may change), and I'm having some issues.
I've created app/Http/Middleware/VerifyCsrfAjaxToken.php with the following:
<?php namespace App\Http\Middleware;
class VerifyCsrfAjaxToken extends VerifyCsrfToken
{
protected function tokensMatch($request)
{
return $request->session()->token() == $request->header('x-csrf-token');
}
}
I then added the following to RouteServiceProvider
protected $middleware = [
// existing middleware
'csrf.ajax' => 'App\Http\Middleware\VerifyCsrfAjaxToken'
]
And finally, my Controller route definition
/**
* @Post("profile/expand", as="expandProfile")
* @Middleware("csrf.ajax")
*
* @return string
*/
public function expandProfile()
{
return 'expanded view';
}
However, when I Ajax in from the view that calls this route, the TokenMismatchException is being thrown from VerifyCsrfToken, and my Ajax Middleware is not being called at all (confirmed by dd() within my Middleware's tokensMatch method not executing).
Is there something basic (or not-so-basic) that I'm missing in this equation?
Please or to participate in this conversation.