Fetch, set-cookies and csrf

前端 未结 2 1750
别那么骄傲
别那么骄傲 2020-12-18 06:45

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

相关标签:
2条回答
  • 2020-12-18 07:26

    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'
            })
        });
    
    0 讨论(0)
  • 2020-12-18 07:41

    Yes header name depends on your server. For example django usecase to setup CSRF token using fetch is like this:

      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=UTF-8',
        'X-CSRFToken': get_token
      },
    
    0 讨论(0)
提交回复
热议问题