Here is a solution for now, refreshing a token needs authentication.
my solution for now is to create a new one after expiration of the old one using Axios Interceptor.
Backend
I've overridden the verify method so i can send ignoreExpiration as an option, otherwise verfiy will throw an error in case the token is expired
const verify = (token) => {
return new Promise(function(resolve, reject) {
jwt.verify(
token,
_.get(strapi.plugins, ['users-permissions', 'config', 'jwtSecret']),
{ignoreExpiration: true},
function(err, tokenPayload = {}) {
if (err) {
return reject(new Error('Invalid token.'));
}
resolve(tokenPayload);
}
);
});
}
module.exports = {
refreshToken: async (ctx) => {
const {token} = ctx.request.body;
const payload = await verify(token);
console.log(payload)
return strapi.plugins['users-permissions'].services.jwt.issue({id: payload.id})
}
}
routes.json
{
"method": "POST",
"path": "/refreshToken",
"handler": "auth.refreshToken",
"prefix": "",
"config": {
"policies": []
}
},
Frontend
i've used axios-auth-refresh to create an interceptor that triggers a refresh token request whenever it detects a 401 Error
import createAuthRefreshInterceptor from 'axios-auth-refresh';
import axios, { AxiosInstance } from "axios";
const refreshAuthLogic = (failedRequest:any) => axios.post(`${SERVER_URL}${REFRESH_TOKEN_URL}`, {token: failedRequest.response.config.headers['Authorization'].split(" ")[1]}).then(tokenRefreshResponse => {
localStorage.setItem('token', tokenRefreshResponse.data);
failedRequest.response.config.headers['Authorization'] = 'Bearer ' + tokenRefreshResponse.data;
return Promise.resolve();
});
createAuthRefreshInterceptor(axiosInstance, refreshAuthLogic);