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.
This commit is contained in:
committed by
GitHub
parent
8aa68be560
commit
ffcf8294f1
@ -1,5 +1,4 @@
|
|||||||
import cookies from 'browser-cookies';
|
import cookies from 'browser-cookies';
|
||||||
|
|
||||||
export const _csrf = typeof window !== 'undefined' && cookies.get('_csrf');
|
|
||||||
export const jwt =
|
export const jwt =
|
||||||
typeof window !== 'undefined' && cookies.get('jwt_access_token');
|
typeof window !== 'undefined' && cookies.get('jwt_access_token');
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import { apiLocation } from '../../config/env.json';
|
import { apiLocation } from '../../config/env.json';
|
||||||
import { _csrf } from '../redux/cookieValues';
|
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import Tokens from 'csrf';
|
import Tokens from 'csrf';
|
||||||
|
import cookies from 'browser-cookies';
|
||||||
|
|
||||||
const base = apiLocation;
|
const base = apiLocation;
|
||||||
const tokens = new Tokens();
|
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
|
// _csrf is passed to the client as a cookie. Tokens are sent back to the server
|
||||||
// via headers:
|
// 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.post['CSRF-Token'] = tokens.create(_csrf);
|
||||||
axios.defaults.headers.put['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) {
|
export function post(path, body) {
|
||||||
|
setCSRFTokens();
|
||||||
return axios.post(`${base}${path}`, body);
|
return axios.post(`${base}${path}`, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
function put(path, body) {
|
function put(path, body) {
|
||||||
|
setCSRFTokens();
|
||||||
return axios.put(`${base}${path}`, body);
|
return axios.put(`${base}${path}`, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user