Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use refresh token in reactjs

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.

like image 872
aditya kumar Avatar asked Jun 06 '20 09:06

aditya kumar


People also ask

How do I trigger a refresh token?

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.

How do I save the refresh token in React JS?

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.

How do you handle token expiration in React?

We need to do 2 steps: – Create a component with react-router subscribed to check JWT Token expiry. – Render it in the App component.

How react refresh token works with demo UI?

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.

What happens when react access token expires?

– 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.

What is a refresh token?

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.

What is @tokenservice in react hooks?

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.


1 Answers

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)
});
like image 82
Mani Ezhumalai Avatar answered Oct 23 '22 08:10

Mani Ezhumalai