fix: fetch CSRF cookie and set headers lazily (#38452)
* fix: fetch csrf cookie and set headers lazily * fix: check cookie each call to keep it up to date Previously the cookie was checked once and never updated until the client was reloaded. Stale or absent cookies would generate incorrect tokens or no tokens, respectively, causing CSRF errors.pull/38460/head
parent
8aa68be560
commit
ffcf8294f1
|
@ -1,5 +1,4 @@
|
|||
import cookies from 'browser-cookies';
|
||||
|
||||
export const _csrf = typeof window !== 'undefined' && cookies.get('_csrf');
|
||||
export const jwt =
|
||||
typeof window !== 'undefined' && cookies.get('jwt_access_token');
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import { apiLocation } from '../../config/env.json';
|
||||
import { _csrf } from '../redux/cookieValues';
|
||||
import axios from 'axios';
|
||||
import Tokens from 'csrf';
|
||||
import cookies from 'browser-cookies';
|
||||
|
||||
const base = apiLocation;
|
||||
const tokens = new Tokens();
|
||||
|
@ -10,7 +10,9 @@ axios.defaults.withCredentials = true;
|
|||
|
||||
// _csrf is passed to the client as a cookie. Tokens are sent back to the server
|
||||
// via headers:
|
||||
if (_csrf) {
|
||||
function setCSRFTokens() {
|
||||
const _csrf = typeof window !== 'undefined' && cookies.get('_csrf');
|
||||
if (!_csrf) return;
|
||||
axios.defaults.headers.post['CSRF-Token'] = tokens.create(_csrf);
|
||||
axios.defaults.headers.put['CSRF-Token'] = tokens.create(_csrf);
|
||||
}
|
||||
|
@ -20,10 +22,12 @@ function get(path) {
|
|||
}
|
||||
|
||||
export function post(path, body) {
|
||||
setCSRFTokens();
|
||||
return axios.post(`${base}${path}`, body);
|
||||
}
|
||||
|
||||
function put(path, body) {
|
||||
setCSRFTokens();
|
||||
return axios.put(`${base}${path}`, body);
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue