32 lines
1.2 KiB
JavaScript
32 lines
1.2 KiB
JavaScript
// src/auth/installAxiosAuthShim.js
|
|
import axios from 'axios';
|
|
|
|
export function installAxiosAuthShim({ debug = false } = {}) {
|
|
axios.defaults.withCredentials = true;
|
|
|
|
axios.interceptors.request.use((config) => {
|
|
try {
|
|
const url = new URL(config.url, window.location.origin);
|
|
const isSameOrigin = url.origin === window.location.origin;
|
|
const isApi = url.pathname.startsWith('/api/');
|
|
if (isSameOrigin && isApi && config.headers) {
|
|
const auth = String(config.headers.Authorization || '').trim();
|
|
if (/^Bearer(\s*(null|undefined)?)?$/i.test(auth)) {
|
|
delete config.headers.Authorization; // let cookie flow
|
|
if (debug) console.debug('[axiosShim] stripped bad Authorization');
|
|
}
|
|
}
|
|
} catch {}
|
|
return config;
|
|
});
|
|
|
|
axios.interceptors.response.use(r => r, (err) => {
|
|
const s = err?.response?.status;
|
|
if ([401,403,419,440].includes(s) && !window.location.pathname.startsWith('/signin')) {
|
|
const next = encodeURIComponent(window.location.pathname + window.location.search);
|
|
window.location.replace(`/signin?session=expired&next=${next}`);
|
|
}
|
|
return Promise.reject(err);
|
|
});
|
|
}
|