Laravel 4 CSRF Token and AJAX (using jQuery)

If you’ve ever ventured into javascript land with your Laravel application and suddenly you don’t have a nice <form> to work with but instead are making ajax calls then you might have wondered how to do CSRF protection. Here’s how easy it is to do ajax csrf protection.

    headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')

That will attach the header X-CSRF-Token to every ajax request you make using jQuery. Notice though that we are getting that csrf token value from a meta field.

<!DOCTYPE html>
<html class="no-js" lang="en" dir="ltr">
	<title>My Page</title>
	<meta name="csrf-token" content="<?= csrf_token() ?>">

Next we need to modify our CSRF token filter in Laravel since out of the box it only looks for Input::get('_token')

Route::filter('csrf', function()
   $token = Request::header('X-CSRF-Token') ?: Input::get('_token');

   if (Session::token() !== $token) {
      throw new Illuminate\Session\TokenMismatchException;

We will still look for _token in the input so we can still use the traditional <form> to submit data in addition to ajax submissions. I haven’t seen any issues with this yet. Of course if I run into any, I’ll be sure to update this post. Have a nice day!

post by Kelt Dockins on 09/18/2013