我使用 Larave+JWT 和 vue2 + vuex2 + axios
因此,当用户登录时,我将身份验证 token 存储在 vuex 存储中。当 token 过期时,我需要刷新它。为了刷新它,我需要将相同的 token 发送到 /refresh
路由,并获得一个新 token 。至少我是这样得到它的,而且它确实有效。
问题是拦截器捕获了 401 响应并尝试刷新 token ,但是如果在我的组件中我发送了许多带有过期 token 的请求怎么办?由于 ajax 请求是异步的,因此拦截器代码会运行多次。所以我收到了很多刷新请求。一旦初始 token 被刷新,它就被认为是无效的。当拦截器尝试刷新无效 token 时,服务器响应错误,我重定向到登录页面。
代码如下:
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true
axios.post('auth/refresh').then((response) => {
let token = response.data.token
store.dispatch('auth/setAuthToken', token)
let authorizationHeader = `Bearer ${token}`
axios.defaults.headers = { 'Authorization': authorizationHeader }
originalRequest.headers['Authorization'] = authorizationHeader
return axios(originalRequest)
}, (error) => {
store.dispatch('auth/clearAuthInfo')
router.push({ name: 'login' })
})
}
return Promise.reject(error);
});
最佳答案
我认为您必须改变刷新 token 的方法。 Auth0
等领导建议主动定期刷新以解决此问题。
Here is a SO answer他们谈论它的地方。
Set the token expiration to one week and refresh the token every time the user open the web application and every one hour. If a user doesn't open the application for more than a week, they will have to login again and this is acceptable web application UX.
关于ajax - 发送许多ajax请求时处理axios拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43081175/