Search code examples
angularjsajaxdrupal-7

CSRF Validation Failed in Drupal 7


I've been searching and searching, including the many topics here, for a solution to my problem. I've had no luck thus far. A bit of a backstory: I'm writing an AngularJS app with Drupal 7 as a backend. I'm able to login without problem, save Session Name and Session ID, and put them together for a Cookie header (I had to use this "hack"). Further, if I made a login call in the Postman app, then tried to update the node, it'd work. It makes me think that there's a problem with session authentication, but I still can't figure it out.

That being said, I'm at a roadblock. Whenever I try to PUT to update a node, I get the following error:

401 (Unauthorized : CSRF validation failed)

Now, my ajax call looks like this:

  $http({
  method: 'PUT',
  url: CONSTANTS.SITE_URL+"/update/node/"+target_nid,
  headers:{
    'Content-Type': CONSTANTS.CONTENT_TYPE,
    'Authentication': CONSTANTS.SESS_NAME +"="+CONSTANTS.SESS_ID,
    'X-CSRF-Token' : CONSTANTS.TOKEN
  },
  data: {
    (JSON stuff)
  }
})

The CONTENT_TYPE is "application/json", the "Authentication" is the band-aid for the Cookie header problem, and the "X-CSRF-Token" is what is (presumably) giving me the problem. SESS_NAME, SESS_ID, and TOKEN are all gathered from the response at Login. I can pull lists made by users on the website, I can pull the list of all of the nodes of a certain type on the website as well. I only run into a problem when I attempt to PUT to update the node.

If I missed any information, let me know and I'll add it!

EDIT: I'm using AngularJS version 1.5.3.


Solution

  • After trying everything else, I followed one of the comments in the thread I linked at the beginning of my original post. They had to comment out a line in Services.module :

    if ($non_safe_method_called && !drupal_valid_token($csrf_token, 'services')) {
      //return t('CSRF validation failed');
    }
    

    It's around line 590, plus or minus a few depending on how much you've messed with the file. I don't like doing it this way, but I can't for the life of me figure out why the token's not working right. It's a temporary fix, for sure, but if someone runs across this with the same problem in the future it'll hopefully help you out!