jQuery add CSRF token to all $.post() requests' data
Asked Answered
A

7

39

I am working on a Laravel 5 app that has CSRF protection enabled by default for all POST requests. I like this added security so I am trying to work with it.

While making a simple $.post() request I received a 'Illuminate\Session\TokenMismatchException' error because the required form input _token was missing from the POST data. Here is an example of a $.post request in question:

var userID = $("#userID").val();
$.post('/admin/users/delete-user', {id:userID}, function() {
// User deleted
});

I have my CSRF token stored as a meta field in my header and can easily access it using:

var csrf_token = $('meta[name="csrf-token"]').attr('content');

Is it possible to append this to the json data on all outgoing $.post() requests? I tried using headers but Laravel did not seem to recognize them -

var csrf_token = $('meta[name="csrf-token"]').attr('content');
alert(csrf_token);
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if (options['type'].toLowerCase() === "post") {
        jqXHR.setRequestHeader('X-CSRFToken', csrf_token);
    }
});
Amoy answered 9/2, 2015 at 19:32 Comment(4)
Do I correctly understand that you want to make your data object have a _token field? (e.g., something like options['data']._token = csrf_token?) A single example of a working request would be helpful, if you have one.Depilate
In order to make the request work I would have to add the token directly to the post data - so {id:userID, '_token':token}Amoy
Okay, so you basically answered in the comment above but not a usable solution - options['data']._token = csrf_token; does not seem to get the job done, but close. Post a working answer, please, and you've got a +1 and accepted answer. :)Amoy
Check this Answer - #53685428Heddie
D
34

Your $.ajaxPrefilter approach is a good one. You don't need to add a header, though; you simply need to add a property to the data string.

Data is provided as the the second argument to $.post, and then formatted as a query string (id=foo&bar=baz&...) before the prefilter gets access to the data option. Thus, you need to add your own field to the query string:

var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if (options.type.toLowerCase() === "post") {
        // initialize `data` to empty string if it does not exist
        options.data = options.data || "";

        // add leading ampersand if `data` is non-empty
        options.data += options.data?"&":"";

        // add _token entry
        options.data += "_token=" + encodeURIComponent(csrf_token);
    }
});

This will turn id=userID into id=userID&_token=csrf_token.

Depilate answered 9/2, 2015 at 19:48 Comment(4)
Okay, I can only get this work with options['data'] = options['data'] + '&_token=' + csrf_token; - the dot notation does not seem to work. It looks better, any idea what the problem might be?Amoy
@Amoy I see; the problem isn't with dot notation, but rather that jQuery transform the data object into a query string before the prefilter gets it. I've edited (but I haven't tested, so let me know if it still breaks).Depilate
@Depilate no, specifically my problem is with ajaxPrefilter. it says options.data is undefined.Kutz
i think my issue might be deeper. i am creating options with $(this).serialize() im thinking it might not be compatible with $.paramKutz
A
41

From Laravel documentation:

You could, for example, store the token in a "meta" tag:

Once you have created the meta tag, you can instruct a library like jQuery to add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

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

So for example you can do request like below.

Add this meta tag to your view:

<meta name="csrf-token" content="{{ csrf_token() }}">

And this is an example script which you can communicate with Laravel (sends request when you click an element with id="some-id" and you can see the response in an element with id="result"):

<script type="text/javascript">
    $(document).ready(function(){

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

        $("#some-id").on("click", function () {
            var request;


            request = $.ajax({
                url: "/your/url",
                method: "POST",
                data:
                {
                    a: 'something',
                    b: 'something else',
                },
                datatype: "json"
            });

            request.done(function(msg) {
                $("#result").html(msg);
            });

            request.fail(function(jqXHR, textStatus) {
                $("#result").html("Request failed: " + textStatus);
            });
        });

    });
</script>
Amorita answered 29/2, 2016 at 20:41 Comment(0)
D
34

Your $.ajaxPrefilter approach is a good one. You don't need to add a header, though; you simply need to add a property to the data string.

Data is provided as the the second argument to $.post, and then formatted as a query string (id=foo&bar=baz&...) before the prefilter gets access to the data option. Thus, you need to add your own field to the query string:

var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if (options.type.toLowerCase() === "post") {
        // initialize `data` to empty string if it does not exist
        options.data = options.data || "";

        // add leading ampersand if `data` is non-empty
        options.data += options.data?"&":"";

        // add _token entry
        options.data += "_token=" + encodeURIComponent(csrf_token);
    }
});

This will turn id=userID into id=userID&_token=csrf_token.

Depilate answered 9/2, 2015 at 19:48 Comment(4)
Okay, I can only get this work with options['data'] = options['data'] + '&_token=' + csrf_token; - the dot notation does not seem to work. It looks better, any idea what the problem might be?Amoy
@Amoy I see; the problem isn't with dot notation, but rather that jQuery transform the data object into a query string before the prefilter gets it. I've edited (but I haven't tested, so let me know if it still breaks).Depilate
@Depilate no, specifically my problem is with ajaxPrefilter. it says options.data is undefined.Kutz
i think my issue might be deeper. i am creating options with $(this).serialize() im thinking it might not be compatible with $.paramKutz
P
14

Generally I agree with the concept Kornel suggested except one thing.

Yes, Laravel's docs advice to use $.ajaxSetup, but it's not recommended since this method affects all the subsequent ajax requests. It is more correctly to set the ajax settings for each request. Though you can re-set stuff:

All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup()

If you use $.ajax(), it's more convenient to utilize either data property or headers. Laravel allows CSRF-token both as a request parameter or a header.

First, you add the following meta tag into the view

<meta name="csrf-token" content="{{ csrf_token() }}">

And then make an ajax request either way:

$.ajax({
    url: "/your/url",
    method: "POST",
    data:
    {
        a: 'something',
        b: 'something else',
        _token: $('meta[name="csrf-token"]').attr('content')
    },
    datatype: "json"
});

OR

$.ajax({
    url: "/your/url",
    method: "POST",
    data:
    {
        a: 'something',
        b: 'something else',
    },
    headers: 
    {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
    datatype: "json"
});
Prorate answered 27/12, 2016 at 13:56 Comment(0)
B
11

The Django documentation on CSRF gives a nice code snippet with ajaxSetup for automatically adding the appropriate header to all request types where it matters:

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
Bahaism answered 23/5, 2017 at 14:29 Comment(0)
L
0

I think that above solution might not work as well. When you do:

var x; 
x + ""
// "undefined" + empty string coerces value to string 

You will get data like "undefined_token=xxx"

When you use the above solution for laravel's delete for instance you have to check like this:

if (typeof options.data === "undefined")
    options.data = "";
else
    options.data += "&";
options.data = "_token=" + csrf_token;
Lamed answered 25/11, 2015 at 3:50 Comment(0)
H
0

there is a much easier method to do this you can serialize the data like so before sending

<form method="post" id="formData">
 <input type="text" name="name" >
 <input type="hidden" name="_token" value="{{ csrf_token() }}">
 <input type="submit" id="sub" class="btn btn-default" value="Submit" />                            
</form>
<script>
    $(document).on('submit', '#formData', function (event) {
    event.preventDefault();
     var formData = $('#formData').serialize();
    $.ajax({
        url: url,
       type: "POST",
       data : formData,   
                success: function (result) {
                    console.log(result);                             
                }
           });
        });

    });
</script>

everything with a name attr will be put in to a query and submited

Hogweed answered 9/4, 2018 at 4:26 Comment(0)
P
0

no need to set any meta tag neither the csrf_token() nor the csrf_field() !

You could use this jQuery snippet :

$.ajaxPrefilter(function( settings, original, xhr ) {
    if (['post','put','delete'].includes(settings.type.toLowerCase())
        && !settings.crossDomain) {
            xhr.setRequestHeader("X-XSRF-TOKEN", getCookie('XSRF-TOKEN'));
    }
});

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

just few other answers tried to set the csrf header but according the Laravel documents (here) , the header key should be "X-XSRF-TOKEN" and Laravel itself provides the needed value on every request for us in a cookie named "XSRF-TOKEN"

so just corrected the keys and edited few lines,thanks

Prophylactic answered 29/4, 2020 at 21:26 Comment(1)
The op might not have access to these cookies. There are lots of ways to configure CSRF tokens and cookies may not be appropriate.Alumroot

© 2022 - 2024 — McMap. All rights reserved.