0
votes

How can I include the token within all your Ajax requests using jQuery and spring security?

At the moment I get the following error

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

Javascript:

function editUser(data) {

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var ctx = location.href.substring(0, location.href.lastIndexOf("/"));
var dataObject = JSON.stringify({ 'username': data });

$.ajax({
      url: ctx+'/users/edit',
      type: 'POST',
      beforeSend: function(xhr){
          xhr.setRequestHeader(header, token);
      },
      data: data
    });
}   

Controller:

@RequestMapping(value = "/users/edit", method = RequestMethod.POST)
public String editUser(@RequestParam("username") String username) {

    System.out.println(username);
    return "users/edit";
}

toLowerCase function is in jQuery

// Caches the header
                setRequestHeader: function( name, value ) {
                    var lname = name.toLowerCase();
                    if ( !state ) {
                        name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
                        requestHeaders[ name ] = value;
                    }
                    return this;
                },
1
I don't see any use of toLowerCase in any of the code you posted. The error is happening somewhere else.Barmar
@Barmar Please see my editQGA
The error indicates that header is undefined.Barmar
I added these in the head of my page and this has fixed the issue <meta name="_csrf" content="${_csrf.token}"/> <meta name="_csrf_header" content="${_csrf.headerName}"/>QGA
Naturally. Your code copies the contents of those meta tags into the AJAX header. Of course it doesn't work if you don't have the tags.Barmar

1 Answers

4
votes

Either make sure that the page always has <meta name="_csrf" content="something"> and <meta name="_csrf_header" content="something"> tags, or have your AJAX code check that the values exist before trying to set the header:

beforeSend: function(xhr) {
    if (header && token) {
        xhr.setRequestHeader(header, token);
    }
}