'Strapi JWT token lifetime?
I can't find any information about JWT token lifetime, how long in will be valid on Strapi CMS?
And how i can automatically refresh the token when it will be not valid?
And how can i do token validation, before i get exeption about token lifetime end? What is name of endpoit link?
Solution 1:[1]
I'm quite confident that the default duration is 30 days and it cannot be reissued using a refresh token.
I think this is an open issue. You can check here for more info:
https://github.com/strapi/strapi/issues/1676#issuecomment-409575253
And it's on the roadmap for future updates:
https://portal.productboard.com/strapi/1-public-roadmap/c/34-refresh-token-jwt
Solution 2:[2]
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);
Solution 3:[3]
Here you can see the default value https://github.com/strapi/strapi/blob/86e0cf0f55d58e714a67cf4daee2e59e39974dd9/packages/strapi-admin/services/token.js
And yes thats 30days
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jessica Simpson |
Solution 2 | |
Solution 3 | Gherciu Gheorghe |