如何使用NodeJS在React应用程序中自动刷新JWT令牌?

时间:2018-05-04 13:30:18

标签: reactjs redux react-redux middleware

最近几天,我尝试编写一些来检查存储在中的令牌是否仍然有效且未达到其到期日期。如果它不再有效,它应该在执行任何其他异步调用之前刷新令牌。我现在遇到的问题是,在调用中间件之前,首先调用组件中的异步redux函数。

目前我编写了以下中间件:

reduxMiddleware.js

const refreshJwt = ({ dispatch, getState }) => {
  return (next) => (action) => {
    console.log(typeof action);
    if (typeof action === "function") {
      if (getState().authentication.token) {
        // decode jwt so that we know if and when it expires

        var tokenExpiration = parseJwt(getState().authentication.token).exp;

        if (
          tokenExpiration &&
          moment(tokenExpiration) <
            moment(Math.floor(Date.now().valueOf() / 1000))._i
        ) {
          console.log("start refreshing");
          startRefreshToken(getState().authentication.refreshToken).then(
            (token) => {
              console.log("done refreshing");
              dispatch(updateAccessToken(token));
              next(action);
            }
          );
        }
      }
    }
    return next(action);
  };
};

export default refreshJwt;

我像这样应用这个中间件:

export default () => {
  const store = createStore(
    combineReducers({
      authentication: authenticationReducer,
      venue: venueReducer,
      tables: tableReducer
    }),
    composeEnhancers(applyMiddleware(refreshJwt, thunk))
  );

  return store;
};

startRefreshToken代码为:

const startRefreshToken = (refresh_token) => {
  return httpPost(
    process.env.NODE_ENV
      ? `https://tabbs-api.herokuapp.com/api/v1/token`
      : `http://localhost:3000/api/v1/token`,
    {
      refresh_token
    }
  )
    .then((response) => {
      localStorage.setItem(
        "authentication",
        JSON.stringify({
          token: response.data.token,
          refreshToken: refresh_token
        })
      );
      return response.data.token;
    })
    .catch((error) => {
      return Promise.reject(error.response);
    });
};

致电顺序:

enter image description here

传奇:

  • 现在执行调用代表组件中调用的函数
  • 开始刷新代表正在调用的中间件

目前我遇到以下问题:

  • 当调用组件didComponentMount中的异步函数时,将在调用中间件函数之前调用它。这导致它将使用存储在redux / local存储中的旧令牌。

到目前为止,我真的无法找到问题,希望能为这个问题获得一些外部帮助。

  

我知道这是重复的:   How to use Redux to refresh JWT token?

感谢您的帮助。如果您需要其他背景/代码,请随时发表评论。我将它添加到codesandbox。

最佳凯文。

0 个答案:

没有答案