I'm having some trouble connecting Drupal 7 and jQuery using Services 3.4 and the jQuery cookie plugin. From what I understand, I need to do the following: - post to the service endpoint /user/login - get session name and session id and add them as an http cookie - get the session token id - add the token id as an http header: X-CSRF-Token: sometoken
I try this method using jQuery and receive an 'Access denied for user anonymous' error. I'm using Services 3.4 with the CORS module across two subdomains. My endpoint appears to be set up correctly and my login function returns user and session data, and I get a token.
I have tested accessing the service from a PHP script based on this example. I modified that example to create nodes as well. It works as expected, respecting Drupal's permissions.
I have made the following change to the header in a custom module after receiving errors about the token being in the header.
function custom_services_init() {
drupal_add_http_header('Access-Control-Allow-Headers', 'X-CSRF-Token');
}
Here is my jQuery code:
$('#menu-connect').click(function() {
var url = 'http://myservice.com/service_endpoint/user/login.json';
$.post(url, { username: 'testuser', password: 'password' }, function(data) {
sessName = data.session_name;
sessId = data.sessid;
$.cookie(sessName, sessId);
// Obtain session token.
$.ajax({
url:"http://myservice.com/services/session/token",
type:"get",
dataType:"text",
error:function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
success: function (token) {
$.ajax({
url: 'http://myservice.com/service_endpoint/user/1.json',
type: "get",
dataType: "json",
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", token);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
success: function (data) {
alert('Hello user #' + data.user.uid);
}
});
}
});
});
});
Just an addition that is included in comment #60 @ https://drupal.org/node/2013781#comment-7764881 (but I missed it 10-times or so).
In jQuery, you have to set the Credentials to be passed. Otherwise, you will never get the cookie for the server to remember you.
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
**NOTE: This usage will affect all ajax calls (which, in my cases, I want, so I use the above method). If you need something different, you could just include it in the $.ajax parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With