[英]How can I use refresh token in react
我有一个像这个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,
}
}
将其保存在本地存储中
export const storeToken = async (token: string) => {
await AsyncStorage.setItem('@token', token);
};
并在需要时从存储中获取
export const getToken = async () => {
return await AsyncStorage.getItem('@token');
};
您可能应该在应用程序启动或从 API 获取时从存储中获取令牌,并在使用应用程序时将其存储在状态等中。
您不应该在本地存储中设置刷新令牌,这会导致安全漏洞,因为本地存储可以通过 javascript 访问,并且由于刷新令牌是长期令牌(比访问令牌寿命更长),您要做的是存储本地存储中的访问令牌,因为访问令牌是短期令牌,存储在本地存储或cookie中是完全可以的,然后您应该在react中进行useEffect()调用,检查令牌何时过期然后进行调用,一个小例子:
import Cookies from 'js-cookie';
axios.get("ur_url_here/",data,{headers:{"Content-Type": "application/json",Accept: "application/json"}}).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/",{headers:{"Content-Type": "application/json",Accept: "application/json"}}).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
}
})
这是一个简化的代码,但应该很好地解释安全刷新令牌的想法。
另请注意,我将访问存储在 cookie 中,但您也可以这样做并将其存储在本地存储中。
您可以使用 LocalStorage 或 SessionStorage。
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")
window.localstorage.setItem('authToken', res.data.token);
// Same as session storage
// window.localstorage.setItem('authToken', res.data.token);
}
}, (err) => {
console.log(err);
})
}
return {
LoginAuth,
}
}
您可以在此处查看差异
Web 应用程序逻辑过程的所有安全措施都通过为您提供访问令牌和刷新令牌来结束,然后您有责任保证它们的安全。 只要这些令牌有效,它们就只是进行访问所需的工件。 实际上,如果您查看 OIDC 流,由于浏览器在安全性方面存在许多已知的弱点,因此大多数访问令牌甚至都没有交给浏览器。
保留或存储这些令牌的最佳方法是在反向通道中处理它们,如果没有,则在浏览器中使用自定义逻辑对其进行加密并存储在本地存储中,以便只有您的应用程序知道如何使用这些令牌。
更好的是让后端代码为您完成这部分,因为您知道 javascript 始终是公开和可检索的。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.