Invalid X-CSRF-Token request header using fetchAPI and Drupal as decoupled back-end












0















First of all, I am a starting developer. I apologize for making possible misconceptions.



I am trying to make a Reactjs application which communicates with a decoupled Drupal 8 back-end by using fetchAPI.



I want to make an authentication system by using session cookies. Getting the cookie from the Drupal site, and setting it in the browser works fine. I can include the cookie in HTTP requests. However, in addition to the cookie, Drupal also wants a 'x-csrf-token' to be included in the HTTP request header. This token can be acquired with a HTTP GET request to the Drupal site. So when a user logs in, I request both the cookie and the x-csrf-token, and I store the token in React's application state using Redux.



Now on the POST request I am trying to make, I get the token from the Redux store and include it in the HTTP request using the 'X-CSRF-Token' header. This gives me a 403 error with the following response: 'X-CSRF-Token request header is invalid'. The exact same request in combination with getting the cookie and token works fine in postman, so I do not know why I am getting this error in the browser.



I tried multiple browsers and different formats for the token, but I still can not get this to work.



(Note: I am using RESTful webservices from Drupal core with cookie authentication enabled.)



Getting the X-CSRF-Token:



export function getCsrfToken() {
return function(dispatch) {
fetch("http://drupalsite.local/rest/session/token", {
method: "GET"
})
.then(res => res.text())
.catch(err => {
console.log(err)
})
.then(token => {
console.log(token);
dispatch({
type: FETCH_CSRF_TOKEN,
payload: token
});
})
.catch(err => {
console.log(err);
});
};
}


The POST request:



export function post(name, csrfToken) {
const data = JSON.stringify({
title: [
{
value: name
}
],
type: [
{
target_id: "test"
}
]
});

return function(dispatch) {
fetch("http://drupalsite.local/node", {
method: "POST",
credentials: "include",
headers: new Headers({
"Content-Type": "application/json",
Accept: "application/json",
"X-CSRF-TOKEN": csrfToken
}),
body: data
})
.then(res => {
dispatch({
type: POST_DATA_CORE_REST,
payload: res
});
})
.catch(err => {
console.log(err);
});
};
}


HTTP headers










share|improve this question























  • drupal.org/project/drupal/issues/2976542 seems possibly relevant

    – sideshowbarker
    Nov 19 '18 at 23:13











  • I do not think it is relevant for my question, because I am sure I have the right token. Thanks for helping though.

    – L. Smans
    Nov 21 '18 at 8:24
















0















First of all, I am a starting developer. I apologize for making possible misconceptions.



I am trying to make a Reactjs application which communicates with a decoupled Drupal 8 back-end by using fetchAPI.



I want to make an authentication system by using session cookies. Getting the cookie from the Drupal site, and setting it in the browser works fine. I can include the cookie in HTTP requests. However, in addition to the cookie, Drupal also wants a 'x-csrf-token' to be included in the HTTP request header. This token can be acquired with a HTTP GET request to the Drupal site. So when a user logs in, I request both the cookie and the x-csrf-token, and I store the token in React's application state using Redux.



Now on the POST request I am trying to make, I get the token from the Redux store and include it in the HTTP request using the 'X-CSRF-Token' header. This gives me a 403 error with the following response: 'X-CSRF-Token request header is invalid'. The exact same request in combination with getting the cookie and token works fine in postman, so I do not know why I am getting this error in the browser.



I tried multiple browsers and different formats for the token, but I still can not get this to work.



(Note: I am using RESTful webservices from Drupal core with cookie authentication enabled.)



Getting the X-CSRF-Token:



export function getCsrfToken() {
return function(dispatch) {
fetch("http://drupalsite.local/rest/session/token", {
method: "GET"
})
.then(res => res.text())
.catch(err => {
console.log(err)
})
.then(token => {
console.log(token);
dispatch({
type: FETCH_CSRF_TOKEN,
payload: token
});
})
.catch(err => {
console.log(err);
});
};
}


The POST request:



export function post(name, csrfToken) {
const data = JSON.stringify({
title: [
{
value: name
}
],
type: [
{
target_id: "test"
}
]
});

return function(dispatch) {
fetch("http://drupalsite.local/node", {
method: "POST",
credentials: "include",
headers: new Headers({
"Content-Type": "application/json",
Accept: "application/json",
"X-CSRF-TOKEN": csrfToken
}),
body: data
})
.then(res => {
dispatch({
type: POST_DATA_CORE_REST,
payload: res
});
})
.catch(err => {
console.log(err);
});
};
}


HTTP headers










share|improve this question























  • drupal.org/project/drupal/issues/2976542 seems possibly relevant

    – sideshowbarker
    Nov 19 '18 at 23:13











  • I do not think it is relevant for my question, because I am sure I have the right token. Thanks for helping though.

    – L. Smans
    Nov 21 '18 at 8:24














0












0








0








First of all, I am a starting developer. I apologize for making possible misconceptions.



I am trying to make a Reactjs application which communicates with a decoupled Drupal 8 back-end by using fetchAPI.



I want to make an authentication system by using session cookies. Getting the cookie from the Drupal site, and setting it in the browser works fine. I can include the cookie in HTTP requests. However, in addition to the cookie, Drupal also wants a 'x-csrf-token' to be included in the HTTP request header. This token can be acquired with a HTTP GET request to the Drupal site. So when a user logs in, I request both the cookie and the x-csrf-token, and I store the token in React's application state using Redux.



Now on the POST request I am trying to make, I get the token from the Redux store and include it in the HTTP request using the 'X-CSRF-Token' header. This gives me a 403 error with the following response: 'X-CSRF-Token request header is invalid'. The exact same request in combination with getting the cookie and token works fine in postman, so I do not know why I am getting this error in the browser.



I tried multiple browsers and different formats for the token, but I still can not get this to work.



(Note: I am using RESTful webservices from Drupal core with cookie authentication enabled.)



Getting the X-CSRF-Token:



export function getCsrfToken() {
return function(dispatch) {
fetch("http://drupalsite.local/rest/session/token", {
method: "GET"
})
.then(res => res.text())
.catch(err => {
console.log(err)
})
.then(token => {
console.log(token);
dispatch({
type: FETCH_CSRF_TOKEN,
payload: token
});
})
.catch(err => {
console.log(err);
});
};
}


The POST request:



export function post(name, csrfToken) {
const data = JSON.stringify({
title: [
{
value: name
}
],
type: [
{
target_id: "test"
}
]
});

return function(dispatch) {
fetch("http://drupalsite.local/node", {
method: "POST",
credentials: "include",
headers: new Headers({
"Content-Type": "application/json",
Accept: "application/json",
"X-CSRF-TOKEN": csrfToken
}),
body: data
})
.then(res => {
dispatch({
type: POST_DATA_CORE_REST,
payload: res
});
})
.catch(err => {
console.log(err);
});
};
}


HTTP headers










share|improve this question














First of all, I am a starting developer. I apologize for making possible misconceptions.



I am trying to make a Reactjs application which communicates with a decoupled Drupal 8 back-end by using fetchAPI.



I want to make an authentication system by using session cookies. Getting the cookie from the Drupal site, and setting it in the browser works fine. I can include the cookie in HTTP requests. However, in addition to the cookie, Drupal also wants a 'x-csrf-token' to be included in the HTTP request header. This token can be acquired with a HTTP GET request to the Drupal site. So when a user logs in, I request both the cookie and the x-csrf-token, and I store the token in React's application state using Redux.



Now on the POST request I am trying to make, I get the token from the Redux store and include it in the HTTP request using the 'X-CSRF-Token' header. This gives me a 403 error with the following response: 'X-CSRF-Token request header is invalid'. The exact same request in combination with getting the cookie and token works fine in postman, so I do not know why I am getting this error in the browser.



I tried multiple browsers and different formats for the token, but I still can not get this to work.



(Note: I am using RESTful webservices from Drupal core with cookie authentication enabled.)



Getting the X-CSRF-Token:



export function getCsrfToken() {
return function(dispatch) {
fetch("http://drupalsite.local/rest/session/token", {
method: "GET"
})
.then(res => res.text())
.catch(err => {
console.log(err)
})
.then(token => {
console.log(token);
dispatch({
type: FETCH_CSRF_TOKEN,
payload: token
});
})
.catch(err => {
console.log(err);
});
};
}


The POST request:



export function post(name, csrfToken) {
const data = JSON.stringify({
title: [
{
value: name
}
],
type: [
{
target_id: "test"
}
]
});

return function(dispatch) {
fetch("http://drupalsite.local/node", {
method: "POST",
credentials: "include",
headers: new Headers({
"Content-Type": "application/json",
Accept: "application/json",
"X-CSRF-TOKEN": csrfToken
}),
body: data
})
.then(res => {
dispatch({
type: POST_DATA_CORE_REST,
payload: res
});
})
.catch(err => {
console.log(err);
});
};
}


HTTP headers







reactjs drupal httprequest fetch-api csrf-protection






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 '18 at 13:08









L. SmansL. Smans

11




11













  • drupal.org/project/drupal/issues/2976542 seems possibly relevant

    – sideshowbarker
    Nov 19 '18 at 23:13











  • I do not think it is relevant for my question, because I am sure I have the right token. Thanks for helping though.

    – L. Smans
    Nov 21 '18 at 8:24



















  • drupal.org/project/drupal/issues/2976542 seems possibly relevant

    – sideshowbarker
    Nov 19 '18 at 23:13











  • I do not think it is relevant for my question, because I am sure I have the right token. Thanks for helping though.

    – L. Smans
    Nov 21 '18 at 8:24

















drupal.org/project/drupal/issues/2976542 seems possibly relevant

– sideshowbarker
Nov 19 '18 at 23:13





drupal.org/project/drupal/issues/2976542 seems possibly relevant

– sideshowbarker
Nov 19 '18 at 23:13













I do not think it is relevant for my question, because I am sure I have the right token. Thanks for helping though.

– L. Smans
Nov 21 '18 at 8:24





I do not think it is relevant for my question, because I am sure I have the right token. Thanks for helping though.

– L. Smans
Nov 21 '18 at 8:24












1 Answer
1






active

oldest

votes


















0














I think I ran into a similar issue, but maybe not. I was searching for for awhile and this post kept coming up so I though I add an answer just incase anyone else stumbles on this.



It turns out that the X-CSRF-Token key was getting multiple values appended to it after the first fetch call. For example:



 1. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
2. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
3. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY


The multiple values triggered the 403 error. I resolved this problem by first checking if the key existed. For example:



let headerCSRF = headers.get('X-CSRF-Token'); 
if ( !headerCSRF ) {
options.headers.append('X-CSRF-Token', csrfToken);
}


Not sure if this is the most elegant solution but it worked for me. This is related to the tutorial on Drupalize.






share|improve this answer
























  • In my case I am sure I only assign one value to the token, so I think you ran into another issue. Thanks for sharing your answer.

    – L. Smans
    Jan 25 at 9:47











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375351%2finvalid-x-csrf-token-request-header-using-fetchapi-and-drupal-as-decoupled-back%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I think I ran into a similar issue, but maybe not. I was searching for for awhile and this post kept coming up so I though I add an answer just incase anyone else stumbles on this.



It turns out that the X-CSRF-Token key was getting multiple values appended to it after the first fetch call. For example:



 1. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
2. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
3. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY


The multiple values triggered the 403 error. I resolved this problem by first checking if the key existed. For example:



let headerCSRF = headers.get('X-CSRF-Token'); 
if ( !headerCSRF ) {
options.headers.append('X-CSRF-Token', csrfToken);
}


Not sure if this is the most elegant solution but it worked for me. This is related to the tutorial on Drupalize.






share|improve this answer
























  • In my case I am sure I only assign one value to the token, so I think you ran into another issue. Thanks for sharing your answer.

    – L. Smans
    Jan 25 at 9:47
















0














I think I ran into a similar issue, but maybe not. I was searching for for awhile and this post kept coming up so I though I add an answer just incase anyone else stumbles on this.



It turns out that the X-CSRF-Token key was getting multiple values appended to it after the first fetch call. For example:



 1. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
2. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
3. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY


The multiple values triggered the 403 error. I resolved this problem by first checking if the key existed. For example:



let headerCSRF = headers.get('X-CSRF-Token'); 
if ( !headerCSRF ) {
options.headers.append('X-CSRF-Token', csrfToken);
}


Not sure if this is the most elegant solution but it worked for me. This is related to the tutorial on Drupalize.






share|improve this answer
























  • In my case I am sure I only assign one value to the token, so I think you ran into another issue. Thanks for sharing your answer.

    – L. Smans
    Jan 25 at 9:47














0












0








0







I think I ran into a similar issue, but maybe not. I was searching for for awhile and this post kept coming up so I though I add an answer just incase anyone else stumbles on this.



It turns out that the X-CSRF-Token key was getting multiple values appended to it after the first fetch call. For example:



 1. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
2. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
3. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY


The multiple values triggered the 403 error. I resolved this problem by first checking if the key existed. For example:



let headerCSRF = headers.get('X-CSRF-Token'); 
if ( !headerCSRF ) {
options.headers.append('X-CSRF-Token', csrfToken);
}


Not sure if this is the most elegant solution but it worked for me. This is related to the tutorial on Drupalize.






share|improve this answer













I think I ran into a similar issue, but maybe not. I was searching for for awhile and this post kept coming up so I though I add an answer just incase anyone else stumbles on this.



It turns out that the X-CSRF-Token key was getting multiple values appended to it after the first fetch call. For example:



 1. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
2. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY
3. x-csrf-token: wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY, wisHtEWaMVIXMe87Rxm5-aTI_M-FdR_pbE4XBZB50cY


The multiple values triggered the 403 error. I resolved this problem by first checking if the key existed. For example:



let headerCSRF = headers.get('X-CSRF-Token'); 
if ( !headerCSRF ) {
options.headers.append('X-CSRF-Token', csrfToken);
}


Not sure if this is the most elegant solution but it worked for me. This is related to the tutorial on Drupalize.







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 24 at 19:53









Nick RiversNick Rivers

1181316




1181316













  • In my case I am sure I only assign one value to the token, so I think you ran into another issue. Thanks for sharing your answer.

    – L. Smans
    Jan 25 at 9:47



















  • In my case I am sure I only assign one value to the token, so I think you ran into another issue. Thanks for sharing your answer.

    – L. Smans
    Jan 25 at 9:47

















In my case I am sure I only assign one value to the token, so I think you ran into another issue. Thanks for sharing your answer.

– L. Smans
Jan 25 at 9:47





In my case I am sure I only assign one value to the token, so I think you ran into another issue. Thanks for sharing your answer.

– L. Smans
Jan 25 at 9:47




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375351%2finvalid-x-csrf-token-request-header-using-fetchapi-and-drupal-as-decoupled-back%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()