最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Strapi JWT token lifetime? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Jul 17, 2020 at 4:26 MrFelixMrFelix 631 gold badge1 silver badge4 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

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./strapi/strapi/issues/1676#issuement-409575253

And it's on the roadmap for future updates:
https://portal.productboard./strapi/1-public-roadmap/c/34-refresh-token-jwt

Here you can see the default value https://github./strapi/strapi/blob/86e0cf0f55d58e714a67cf4daee2e59e39974dd9/packages/strapi-admin/services/token.js

And yes thats 30days

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);

for this you just need go to file \node_modules@strapi\plugin-users-permissions\server\config.js find the lines: jwt: { expiresIn: '30d', }, and set as many as you need... for example (two hours): jwt: { expiresIn: '2h', }, then restart strapi server

In strapi v4 you can set it in config/plugins.js and then per environment, config/development/plugins.js etc

module.exports = ({ env }) => ({
  // ...
  'users-permissions': {
    config: {
      jwt: {
        expiresIn: '60s',
      },
    },
  },

restart the server and your tokens should expire in 60 seconds. This isn't suitable for production and you need refresh routines etc.

https://forum.strapi.io/t/how-to-set-jwt-expiration-to-years/5490/3

发布评论

评论列表(0)

  1. 暂无评论