I have a site where a custom form is in opened in a modal, and when submitted calls an ajax function to POST to a REST service to create a node.
The problem is I keep getting "Forbidden" response upon submission.
I only want logged in users to be able to send these ajax requests and the auth should be different token for each user.
Here is my code:
$('#create-node-submit').click(function(e) {
e.preventDefault();
var newNode = {
_links: {
type: {
href: 'http://mysite.dev/rest/type/node/article'
}
},
type: {
target_id: 'article'
},
title: {
value: 'This is a test Article from REST'
},
field_description: {
value: 'Here is some test description.'
}
};
getCsrfToken(function (csrfToken) {
postNode(csrfToken, newNode);
});
return false;
});
function getCsrfToken(callback) {
$.get(Drupal.url('rest/session/token'))
.done(function (data) {
var csrfToken = data;
callback(csrfToken);
});
}
function postNode(csrfToken, node) {
$.ajax({
url: 'http://mysite.devdev/entity/node?_format=hal_json',
method: 'POST',
headers: {
'Content-Type': 'application/hal+json',
'X-CSRF-Token': csrfToken
},
data: JSON.stringify(node),
success: function (node) {
console.log(node);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
When running a test in POSTMAN it is successful, but the authentication was slightly different there:
As you can see in the picture, I get 201 created when using POSTMAN.
I believe it has to do with the CSRF token being used in the Javascript implementation. I'm not sure what authentication method I'm supposed to use when POSTing to the same site via JS.
I used the information here.
I created a bug report as it seems the CSRF token check passes successfully and grants access, but access is denied from somewhere else. Issue #2831251 Trying to create nodes via REST with ajax POST request returns 403 response