【问题标题】:Proper workflow for refreshing expired JWT token automatically on request using Axios interceptor and httpOnly cookies使用 Axios 拦截器和 httpOnly cookie 根据请求自动刷新过期 JWT 令牌的正确工作流程
【发布时间】: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


    【解决方案1】:

    这种方法看起来不错,不过,如果我没记错的话,这不是标准的 OAuth 刷新流程,对吧?在我看来,实施标准总是更好,尤其是在涉及安全性时。

    使用这种方法可能会遇到一个问题。如果expiration 是一秒钟后,您的代码将不会触发,但当访问令牌到达服务器时,它可能已过期。如果客户端计算机和服务器之间的时钟存在差异,也会发生这种情况。

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 2020-01-25
      • 1970-01-01
      • 2020-01-13
      • 2019-01-09
      • 2018-06-02
      • 2021-01-23
      • 2021-07-13
      • 2021-05-17
      相关资源
      最近更新 更多