Comment the line in app/Http/Kernel.php
'App\Http\Middleware\VerifyCsrfToken',
Excluding middleware csrf
Since the latest update the CSRF middleware is part of the core and I'm not able to disable it anymore.
I want to send a simple AJAX post to a controller but getting a TokenMismatch exception. Any idea if I can EXCLUDE routes from using middleware by annotation? Something like @Middleware(exclude="csrf")?
Ah all initial middlewares have been moved there, thank you @az_iar! In general it is a good idea using this middleware as default in every post request but for an API controller or sth it won't work. So having the option to remove it globally and using it explicit is a great solution.
As a side point - there is normally no need to disable CSRF for Ajax. You can easily include the token in your Ajax form, and pass it along with the request.
By disabling the CSRF check for Ajax - you open a small risk of a CSRF attack relating to that function.
@theshiftexchange tried it by generating the token using csrf_token() and submitting it as field "_token". But still getting the exception. What did I wrong?
Btw: I'm not a big fan of disabling it, too. So getting it run with sending the token would be the best solution.
It is a bit hard to tell without seeing your code - but you need something like this in your form:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Then in your ajax function something like this:
$(document).ready( function() {
var form = $('#my_awesome_form');
$.ajax({
url: form[0].action,
type: form[0].method,
data: form.serialize(),
dataType: 'json',
success: function(data)
{
alert('yay');
}
});
If it is still failing - you'll need to do some local debugging. Check your POST and make sure the _token is there. etc
It's working perfect! Did the mistake creating multiple CSRF tokens which resulted in the exception. Everything is fine now, with CSRF middleware in AJAX requests!
If you want to disable CSRF on specific routes then follow this tutorial http://www.techigniter.in/tutorials/disable-csrf-check-on-specific-routes-in-laravel-5/
I know the topic is 5-months-old but today I struggle with the same problem.
I wanted to avoid only the API calls so comment the middleware was not an option. I decide to bypass the CSRF in the API calls like that
Disclaimer: All the routes of the API starts with ENDPOINT/api/...
class VerifyCsrfToken extends BaseVerifier {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(strpos($request->getRequestUri(), 'api') >= 0)
{
return $next($request);
}
return parent::handle($request, $next);
}
}
You can now use the protected $except in the VerifyCsrfToken class to define 'excepted' routes: http://laravel.com/docs/master/routing#csrf-excluding-uris (5.1)
Please or to participate in this conversation.