I am working on a admin app in reactjs which uses redux for state management. In my app when user log in it gets access_token
and refresh _token
. access_token
which gets expired after 5 min. after 5 min token becomes invalid to make any api endpoint request.
I want to know how am I suppose to use this refresh_token
to update my access_token
which is stored in localStorage
of the browser. I had no idea about this refresh_token
before this. This is how I make login request and save my access_token
and refresh_token
.
authentication:
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");
}
};
I did read about this in some of the blog post but i did get this. https://nmajor.com/posts/access-and-refresh-token-handling-with-redux Any help would be highly appreciated.
To use the refresh token, make a POST request to the service's token endpoint with grant_type=refresh_token , and include the refresh token as well as the client credentials if required.
Storing refresh tokens via silent authentication involves sending a request to the identity server to get an access token whenever there is an API request or during page refresh. If your session still remains, the identity provider will return a valid token.
We need to do 2 steps: – Create a component with react-router subscribed to check JWT Token expiry. – Render it in the App component.
Let’s see how the React.js Refresh Token works with demo UI. – First we make an account login. – Now user can access resources with available Access Token. – When the Access Token is expired, React automatically send Refresh Token request, receive new Access Token and use it with new request.
– When the Access Token is expired, React automatically send Refresh Token request, receive new Access Token and use it with new request. – After a period of time, the new Access Token is expired again, and the Refresh Token too. Now the user cannot access restricted resources.
That is, a refresh token is a credential artifact that lets a client application get new access tokens without having to ask the user to log in again. In the diagram above, SPA = Single-Page Application; AS = Authorization Server; RS = Resource Server; AT = Access Token; RT = Refresh Token.
TokenService provides get, set, remove methods to work with Token and User Data stored on Browser. If you use code in React Hooks: JWT Authentication (without Redux) example, you can modify services like this.
You can add token expiry time validation on app.js so if you reload you application or move to next page or if you make api call it will check token expiry time validation always if token expired it will make call to fetch update token
check below example : i gave example with react axios
axios.interceptors.request.use(async (config) => {
const expireAt = localStorage.getItem('expiresAt');
let token = localStorage.getItem('authToken');
if (dayjs(expireAt).diff(dayjs()) < 1) {
const data = onGetForcedToken();
token = typeof data === 'string' ? data : await data();
}
// setting updated token
localStorage.setItem('authToken', token);
return config;
}, (err) => {
console.log("error in getting ",err)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With