Manage bearer token in api calls #172
-
Hello, I'm trying to make calls with my auth tokens and i was wondering if there is any way to do it globally without passing it on each call ? Is there also a way to add a middleware function on the request (to call the refresh token endpoint if the access expire) ? Thanks for your amazing work 👏 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hey @quentinfon, as we are using Axios for API calls, you can easily use interceptors to add authorization headers, as well as to refresh tokens. // api/client.ts
import {Env} from '@env';
import type {AxiosRequestConfig} from 'axios';
import axios from 'axios';
import createAuthRefreshInterceptor from 'axios-auth-refresh';
import {refreshAuthLogic} from './refresh-auth-logic';
export const client = axios.create({
baseURL: Env.API_URL,
});
//Once you have logged in and received the token, you should set the token using this function
export const setHeaderToken = (token: string) => {
if (token) {
client.defaults.headers.common.Authorization = `Bearer ${token}`;
}
};
// call this on logout
export const removeHeader = () => {
client.defaults.headers.common.Authorization = null;
};
createAuthRefreshInterceptor(client, refreshAuthLogic, {
statusCodes: [401], // default: [ 401 ]
pauseInstanceWhileRefreshing: true,
}); And based on your backend you can implement the refresh token logic, here is a simple implementation: // api/refresh-auth-logic.ts
export const refreshAuthLogic = async (failedRequest: any) => {
const token = getToken();
if (!token || (token && !token.access)) {
return new Promise((resolve, _reject) => {
resolve(null);
});
}
return new Promise((resolve, reject) => {
axios
.post(
`${Env.API_URL}auth/token/refresh`,
{
refresh: token.refresh,
},
{
headers: {
'Content-Type': 'application/json',
},
}
)
.then(({ data }) => {
if (data?.access) {
setTokenData(data);
failedRequest.response.config.headers.Authorization =
'Bearer ' + data.access;
}
resolve(data);
})
.catch((err) => {
signOut();
reject(err);
});
});
}; I hope this can help, and let me know if it is working in your case. |
Beta Was this translation helpful? Give feedback.
-
It's working perfectly thank you so much 💯 |
Beta Was this translation helpful? Give feedback.
Hey @quentinfon, as we are using Axios for API calls, you can easily use interceptors to add authorization headers, as well as to refresh tokens.
Here is a complete example on how to do it