javascript - 我如何在 react 中使用刷新 token

我有一个像这样的获取刷新 token url client.com/api//auth/refresh-token。但我很难使用它。我认为它应该在登录后在本地存储中保存一个刷新 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,
    }
}

最佳答案

您不应该在本地存储中设置刷新 token ,这会导致安全漏洞,因为本地存储可以通过 javascript 访问,并且刷新 token 是长期 token (比访问 token 生命周期长),您要做的是, 将访问 token 存储在本地存储中,因为访问 token 是短期 token ,存储在本地存储或 cookie 中完全没问题,然后你应该在 react 中调用 useEffect() ,检查 token 是否过期,然后进行调用,一个小例子:

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
}
},[])

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

另请注意,我将访问权限存储在 cookie 中,但您也可以这样做并将其存储在本地存储中。

https://stackoverflow.com/questions/72410388/

相关文章:

javascript - 如何在 redux-toolkit 中输入 'prepare' 函数

c# - 自定义类作为 C# 中字典的键不起作用

python - 我的错误在哪里?在Python中检查密码是否正确

python - 通过多级函数传递 kwargs,解包其中一些但传递所有函数

awk - 在 text.file 中切换列

java - Spring Boot-2.1.3 : Parallel Methods Invoca

r - 如何在循环中获取标签

python - 如何在 Python 中对列表进行排序和过滤?

vector - 将具有多个参数的函数应用于 Julia 中的向量

python - 计算数据框 Pandas 的多列中某个值的出现次数