我有一个像这样的获取刷新 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/