我正在使用ReactJS开发一个管理应用程序,其中使用Redux进行状态管理。当用户登录时,我的应用程序会获取access_token
和refresh_token
。access_token
在5分钟后会过期,此时token将变得无效,无法进行任何API端点请求。
我想知道如何使用refresh_token
来更新存储在浏览器的localStorage
中的access_token
。在此之前,我对refresh_token
一无所知。以下是我的登录请求和保存access_token
和refresh_token
的方式。
认证:
export const Authentication = async(payload) =>{
try{
const response = await fetch(`${generalConfig.baseURL}/oauth/token`, {
method: 'POST',
cache: 'no-cache',
headers: {
'Authorization': `Basic ${btoa("topseller:topseller")}`,
'Accept': '*/*',
// 'Content-Type': 'multipart/form-data',
'accept-encoding': 'gzip, deflate',
},
body: payload
})
.then((response)=>{
console.log(response)
return response.json()
},err=>{
console.log(err,'############')
})
console.log(response,'@@@@@@@@@')
return response;
}catch(err){
console.log(err,'############')
}
}
authentication.action:
export const getAccessToken = (dataToSend) => async (dispatch) => {
try {
var formData = ConvertToFormData(dataToSend);
const authResponse = await Authentication(formData);
<-- See above about this Authentication function
const response = await fetch("http://api.smartocart.com/userType", {
method: "GET",
cache: "no-cache",
headers: {
Authorization: `Bearer ${authResponse.access_token}`,
},
});
const payload = await response.json();
if (payload.status === "admin") {
SaveToLocalStorage("access_token", authResponse.access_token);
SaveToLocalStorage("refresh_token", authResponse.refresh_token);
dispatch({
type: GET_ACCESS_TOKEN,
payload: {
access_token: authResponse.access_token,
refresh_token: authResponse.refresh_token,
},
});
} else {
dispatch({
type: ERROR_ACCESS_TOKEN,
buttonPressed: true,
});
}
} catch (exception) {
console.log("Log In again");
}
};
我在一些博客文章中读到了这个,但是我并没有理解。 https://nmajor.com/posts/access-and-refresh-token-handling-with-redux 非常感谢您的帮助。
dayjs
是什么?你能解释一下吗? - aditya kumar