gpt4 book ai didi

javascript - 如何在不中断异步流程的情况下在 redux 中自动刷新 JWT?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:24:16 24 4
gpt4 key购买 nike

高级描述

我有一个使用 Google Oauth 的 React/redux/electron 应用程序。我希望能够在访问 token 过期时自动刷新它。我对此进行了研究并使用中间件成功地解决了它,但我的解决方案在某些情况下会出错。

我已经实现了一个在每个 API 操作上运行的刷新中间件。它检查访问 token 是否已过期或即将过期。如果是这样,它不会分派(dispatch)它收到的操作,而是分派(dispatch) token 刷新操作并将任何其他操作排队,直到收到新的访问 token 。之后,它会调度其队列中的所有操作。

但是,我的一个 Action 创作者看起来像这样:

function queryThreads(params) {
return async (dispatch) => {
const threads = await dispatch(fetchThreads(params))
const newPageToken = threads.payload.nextPageToken
}
}

当刷新中间件由于 token 未过期而未运行时,threads.payload 将在此处定义,一切都将按预期工作。

但是,当刷新中间件确实运行时,threads.payload 将是undefined,因为 dispatch 似乎使用 token 刷新操作,而不是 fetchThreads 操作。

我如何确保 token 得到刷新(并在 state/localStorage 中更新),fetchThreads 与更新后的 token 一起分派(dispatch),并且 threads 变量被分配给正确 Promise 的解析值?

项目代码链接

This is my refresh middleware .它的灵感来自 this article通过 kmmbvnr .

This is the token refresh action creator .

This is the line in my queryThreads action creator当 token 必须刷新时抛出(threads.payloadundefined)。

This is the reducer where I update state响应 token 刷新。

This is the middleware where I update localStorage响应 token 刷新。

最佳答案

看起来我已经通过像这样重写刷新中间件解决了这个问题:

function createRefreshMiddleware() {
const postponedRSAAs = [];
return ({ dispatch, getState }) => {
const rsaaMiddleware = apiMiddleware({ dispatch, getState });
return next => action => {
if (isRSAA(action)) {
try {
const auth = JSON.parse(localStorage.getItem('auth'));
const { refresh_token: refreshToken } = auth;
const expirationTime = jwtDecode(auth.id_token).exp * 1000;
const isAccessTokenExpiring =
moment(expirationTime) - moment() < 300000;

if (refreshToken && isAccessTokenExpiring) {
postponedRSAAs.push(action);
if (postponedRSAAs.length === 1) {
return rsaaMiddleware(next)(
dispatch(() => attemptTokenRefresh(refreshToken))
).then(() => {
const postponedRSAA = postponedRSAAs.pop();
return dispatch(postponedRSAA);
});
}
return rsaaMiddleware(next)(action);
}
return rsaaMiddleware(next)(action);
} catch (e) {
console.log(e);
return next(action);
}
}
return next(action);
};
};
}

export default createRefreshMiddleware();

现在推迟的 Action 将始终与 token 刷新 Action 链接在一起,所以我们没有原始 promise 解析错误值的问题;而且它更简洁。

关于javascript - 如何在不中断异步流程的情况下在 redux 中自动刷新 JWT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52282005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com