-
-
Save ericlbarnes/6010796 to your computer and use it in GitHub Desktop.
Laravel CSRF Ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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) { | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<meta name="token" content="{{ Session::token() }}"> |
thanks!
Appreciate this solution, took me a while to stumble onto this. Thanks!
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
Nice!