最近几天,我尝试编写一些middleware来检查存储在redux-store中的令牌是否仍然有效且未达到其到期日期。如果它不再有效,它应该在执行任何其他异步调用之前刷新令牌。我现在遇到的问题是,在调用中间件之前,首先调用组件中的异步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);
});
};
致电顺序:
传奇:目前我遇到以下问题:
到目前为止,我真的无法找到问题,希望能为这个问题获得一些外部帮助。
我知道这是重复的: How to use Redux to refresh JWT token?
感谢您的帮助。如果您需要其他背景/代码,请随时发表评论。我将它添加到codesandbox。
最佳凯文。