-
Notifications
You must be signed in to change notification settings - Fork 0
Port axios interceptors as template samples #25
Description
Is your feature request related to a problem? Please describe.
No
Describe the solution you'd like
As other applications are being developed we have quite a consice description of how axios is being used with react-query and orval, this includes the use of an interceptor to add the token every time a request is sent to the server
/**
* Add the token before each request
*/
axios.interceptors.request.use(config => {
if(config.headers) {
const accessToken = window.localStorage.getItem('access_token');
axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
}
return config;
}, error => {
});and another that redirects the user to the authentication page if we receive a 401 response from the server. This is thus handled globally across the application:
/**
* If the response is unautorised then goto the
* login page
*/
axios.interceptors.response.use((config) => {
return config;
}, (error) => {
if(error.response.status === 401) {
window.location.href = '/auth/login';
}
return Promise.reject(error);
});The login action ends up writing the access_token to the localstorage:
/**
* Call the authentication end point and on success stores
* the access token in the query client and redirects to the
* landing interface for the current user
*
* @param queryClient
* @returns
*/
export const action = (queryClient: QueryClient) =>
async({ request } : any) => {
const formData = await request.formData();
const loginInfo = Object.fromEntries(formData);
await loginForAuthToken({
username: loginInfo.username,
password: loginInfo.password,
}).then((response) => {
window.localStorage.setItem(
'access_token',
response.data?.access_token
);
}).catch((error) => {
console.log(error);
});
return redirect('/admin/users');
};The above code samples should thus be merged into index.tsx as part of the application template.
Note: that the authentication endpoints are based on what the
python-servercurrently provides
Describe alternatives you've considered
Code samples provided above
Additional context
Refer to security documentation for access_tokens