我正在使用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);
}
);
编辑
我遇到了一个问题,需要检查重置身份验证的代码在用户复制直接网址时不起作用。
app.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.