Skip to content

Instantly share code, notes, and snippets.

@ericlbarnes
Forked from anonymous/filters.php
Created July 16, 2013 17:30
Show Gist options
  • Save ericlbarnes/6010796 to your computer and use it in GitHub Desktop.
Save ericlbarnes/6010796 to your computer and use it in GitHub Desktop.
Laravel CSRF Ajax
/**
* Filter to check for CSRF attacks from the ajax requests.
*/
Route::filter('csrf_header', function()
{
if (Session::token() != Request::header('x-csrf-token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
$.ajax({
url: 'post/add',
type: 'post',
dataType: 'json',
data: this.data,
beforeSend: function(request) {
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
},
success: function(ev) {
},
error: function(xhr, error, status) {
}
});
<meta name="token" content="{{ Session::token() }}">
@ux-engineer
Copy link

Nice!

@pilot911
Copy link

thanks!

@shampine
Copy link

Appreciate this solution, took me a while to stumble onto this. Thanks!

@i3zhe
Copy link

i3zhe commented Jan 30, 2015

Thanks, man. One thing to notice, the CSRF Vulnerability In Laravel 4 from the official blog:

http://blog.laravel.com/csrf-vulnerability-in-laravel-4/

So a quick fix:

if (Session::token() !== Request::header('x-csrf-token')) {
    throw new Illuminate\Session\TokenMismatchException;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment