如何在反应中使用刷新令牌

Jul*_*fer 4 javascript typescript reactjs

我有一个像这样的获取刷新令牌网址client.com/api//auth/refresh-token。但我很难使用这个。我认为登录后应该在本地存储中保存刷新令牌。但我该如何使用它呢?

登录.tsx

export const useLogin = () => {

    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(baseURL + `client/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                console.log("success")
            }
        }, (err) => {
            console.log(err);
        })
        
    }
    return {
        LoginAuth,
    }
}
Run Code Online (Sandbox Code Playgroud)

Gha*_*azi 8

您不应该在本地存储中设置刷新令牌,这会导致安全漏洞,因为本地存储可以通过 javascript 访问,并且刷新令牌是长期令牌(比访问令牌寿命长),所以您要做的就是存储本地存储中的访问令牌,由于访问令牌是短期令牌,存储在本地存储或cookie中是完全可以的,然后您应该在react中进行 useEffect() 调用,每当令牌过期时进行检查,然后进行调用,一个小例子:

import Cookies from 'js-cookie';
axios.get("ur_url_here/",data,{withCredentials:true}).then((res)=>{
                Cookies.set(res.data.access) // assuming the response has the access token
        
}))

// now we check the expiration of access token

useEffect(()=>{
   if(!(Cookies.get("access"))){
      axios.get("refresh_url_here/",{withCredentials:true}).then((res)=>{
        Cookies.set(res.data.access)
})
/*what you do here, is try to have a 
resource/view in your backend that has 
the refresh token and make request to it 
so that it gives you a new access token, 
because refresh token should be in cookies tagged with `httponly', 
then you can send the access token to client side 
as a response and set it somewhere.
*/
}
   else{
      //do something else
}
},[])
Run Code Online (Sandbox Code Playgroud)

这是一个简化的代码,但应该很好地解释安全刷新令牌的想法。

另请注意,我将访问权限存储在 cookie 中,但您也可以执行相同的操作并将其存储在本地存储中。

  • 这意味着您正在构建一个可以设置 HttpOnly cookie 的有状态 API。提供的解决方案不适用于客户端和后端位于不同顶级域的无状态 API。 (2认同)