我正在使用 reactjs、mbox 和 axios 并遇到了问题。我有一个提供访问令牌和刷新令牌的 api。访问令牌每 20 分钟消失一次,当这种情况发生时,服务器会发回 401,我的代码将自动发送刷新令牌以获取新的访问令牌。
一旦授予新的访问令牌,将再次发送相同的拒绝请求。现在我的代码运行良好,直到我抛出多个几乎可以同时触发的拒绝。
所以第一个请求关闭,401 被发回并获得一个新的刷新令牌,所有其他请求都将尝试做同样的事情,但其他请求现在将失败,因为将使用刷新令牌和一个新的将发出第一个请求。
这将启动我的代码以将用户重定向到登录页面。
所以基本上我一次只能有 1 个请求。
export const axiosInstance = axios.create({
baseURL: getBaseUrl(),
timeout: 5000,
contentType: "application/json",
Authorization: getAuthToken()
});
export function updateAuthInstant() {
axiosInstance.defaults.headers.common["Authorization"] = getAuthToken();
}
function getAuthToken() {
if (localStorage.getItem("authentication")) {
const auth = JSON.parse(localStorage.getItem("authentication"));
return `Bearer ${auth.accessToken}`;
}
}
axiosInstance.interceptors.response.use(
function(response) {
return response;
},
function(error) {
const originalRequest = error.config;
if (error.code != "ECONNABORTED" && error.response.status === 401) {
if (!originalRequest._retry) {
originalRequest._retry = true;
return axiosInstance
.post("/tokens/auth", {
refreshToken: getRefreshToken(),
grantType: "refresh_token",
clientId : "myclient"
})
.then(response => {
uiStores.authenticaionUiStore.setAuthentication(JSON.stringify(response.data))
updateAuthInstant();
return axiosInstance(originalRequest);
});
} else {
uiStores.authenticaionUiStore.logout();
browserHistory.push({ pathname: '/login',});
}
}
return Promise.reject(error);
}
);
编辑
我遇到问题,当用户在直接 url 中复制时,我需要检查以重置身份验证的代码不起作用
应用程序.js
<React.Fragment>
<Switch>
<Route path="/members" component={MemberAreaComponent} />
</Switch>
</React.Fragment >
在 memberAreaComponent
<Route path="/members/home" component={MembersHomeComponent} />
当我输入http://www.mywebsite/members/home
MembersHomeComponent - componentDidMount runs first
MemberAreaComponent - componentDidMount runs second
AppCoontainer = componentDidMount runs last.