【发布时间】:2021-08-29 23:44:40
【问题描述】:
您好,我正在尝试找出使用 Axios 和 httpOnly cookie 刷新过期 JWT 令牌的正确工作流程。 我看过一些向服务器发出请求的教程,如果他们收到“过期令牌响应”,那么他们会发送 401“刷新令牌”请求。
但我认为最好只检查客户端上的令牌是否已过期,这样我们就不会浪费服务器响应它已过期的 HTTP 请求。
这是我到目前为止的代码。我想知道是否有更好或更简单的方法。如果还有其他我不考虑的事情。 非常感谢
// Create Axios instance for Backend API
const BACKEND_URL = 'http://localhost:8000/'
const API = axios.create({
baseURL: BACKEND_URL,
})
// Axios interceptor to refresh token when expired
API.interceptors.request.use(async (config) => {
// If Authorization header exists get token from header and decode it to get expiration time
const authorizationHeader = config.headers.common.Authorization
if (authorizationHeader) {
const token = authorizationHeader.replace('Bearer ', '')
const expiration = jwt_decode(token).exp
// If token has expired get a new one and update Authorization Header
if (Date.now()/1000 >= expiration) {
// Delete Authorization header to prevent infinite loop
delete API.defaults.headers.common.Authorization
// Send /token/refresh request to backend
const response = await API.post(`auth/token/refresh/`, {}, {withCredentials: true})
// Update header in current request
config.headers.common.Authorization = `Bearer ${response.data.access}`
// Update header in the axios instance
API.defaults.headers.common['Authorization'] = `Bearer ${response.data.access}`
}
}
return config
})
【问题讨论】:
标签: javascript axios jwt