mfr*_*het 4 javascript cookies fetch
我在我的应用程序中使用Isomorphic fetch,我遇到了一些处理CSRF的麻烦.
实际上,我有一个后端,在set-cookies属性中发送了CSRF-TOKEN:
我在某处读过这是不可能的,或者直接在我的代码中访问这种cookie是一种不好的做法.
这样,我尝试使用fetch request的credentials属性创建一些东西:
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'
            })
        });
Run Code Online (Sandbox Code Playgroud)
这样,我就可以将我的CSRF cookie发送回我的服务器来满足我的需求(这是一个不同的,因为它不是同一个请求):
我的问题
我的问题是我的后端需要接收x-csrf-token标头,因此我无法将其设置为我的POST请求.
我需要的
如何将set-cookies:CSRF-TOKEN的值放入下一个请求x-csrf-token标头?
在您的场景中,您应该从CSRF-TOKEN cookie中读取.否则它会被标记为HttpOnly为JSESSIONID.后者意味着您无法从网页访问它,而只是自动发回服务器.
一般来说,从cookie中读取CSRF令牌没有错.请检查一下这个好的讨论:为什么在CSR中放置CSRF预防令牌很常见?
您可以使用以下代码读取您的cookie(不是HttpOnly,原因)
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]);
}
Run Code Online (Sandbox Code Playgroud)
所以fetch call看起来像
const csrfToken = getCookie('CSRF-TOKEN');
const headers = new Headers({
        'Content-Type': 'x-www-form-urlencoded',
        'X-XSRF-TOKEN': csrfToken
    });
    return this.fetcher(url, {
        method: 'POST',
        headers,
        credentials: 'include',
        body: JSON.stringify({
            email: 'mail@mail.fr',
            password: 'password'
        })
    });
Run Code Online (Sandbox Code Playgroud)
        是的标头名称取决于您的服务器。例如,使用 fetch 设置 CSRF 令牌的 django 用例如下:
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=UTF-8',
    'X-CSRFToken': get_token
  },
Run Code Online (Sandbox Code Playgroud)