Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I m using Isomorphic fetch in my application and I m having some troubles dealing with CSRF.

Actually, I m having a backend that sends me a CSRF-TOKEN in set-cookies property :

enter image description here

I have read somewhere that it's not possible, or it's a bad practice to access this kind of cookies directly inside of my code.

This way, I tried to make something using the credentials property of fetch request :

const headers = new Headers({
            'Content-Type': 'x-www-form-urlencoded'
        });
        return this.fetcher(url, {
            method: 'POST',
            headers,
            credentials: 'include',
            body: JSON.stringify({
                email: 'mail@mail.fr',
                password: 'password'
            })
        });

This way, I m able to send my CSRF cookie back to my server to serve my need (it's a different one, because it s not the same request) :

enter image description here

My problem

My problem is that my backend needs to receive a x-csrf-token header and so I can't set it to my POST request.

What I need

How can I do to put the value of set-cookies: CSRF-TOKEN into the next request x-csrf-token header ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
257 views
Welcome To Ask or Share your Answers For Others

1 Answer

It looks like in your scenario you are supposed to read from CSRF-TOKEN cookie. Otherwise it would be marked HttpOnly as JSESSIONID. The later means you cannot access it from the web page but merely send back to server automatically.

In general there is nothing wrong in reading CSRF token from cookies. Please check this good discussion: Why is it common to put CSRF prevention tokens in cookies?

You can read your cookie (not HttpOnly, of cause) using the following code

function getCookie(name) {
  if (!document.cookie) {
    return null;
  }

  const xsrfCookies = document.cookie.split(';')
    .map(c => c.trim())
    .filter(c => c.startsWith(name + '='));

  if (xsrfCookies.length === 0) {
    return null;
  }
  return decodeURIComponent(xsrfCookies[0].split('=')[1]);
}

So fetch call could look like

const csrfToken = getCookie('CSRF-TOKEN');

const headers = new Headers({
        'Content-Type': 'x-www-form-urlencoded',
        'X-CSRF-TOKEN': csrfToken
    });
    return this.fetcher(url, {
        method: 'POST',
        headers,
        credentials: 'include',
        body: JSON.stringify({
            email: 'test@example.com',
            password: 'password'
        })
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...