简体   繁体   中英

Refresh and Access token issue axios and react native

// I have the following code

// this is for refreshing the token and it works perfectly fine

export async function refreshTokenGenerator() {

  const url = RefreshCurrentTokenURL;

  const refreshTokenGeneratedFirst = newUser.getRefreshToken();

  const response = await axios
    .post(url, {

      refreshToken: refreshTokenGeneratedFirst,
    })
    .catch((error) => {

      console.log(
        "🚀 ~ file: auth.js:118 ~ refreshTokenGenerator ~ error cant refresh token",
        error
      );
    });

  const newRefreshTokenGenerated = response.data.refreshToken;

  //  assign the new generated refresh token to the user model

  // Refresh token loop works fine, no error from overriding the RT

  const assignNewRefreshTokenToUserModel = newUser.setRefreshToken(
    newRefreshTokenGenerated
  );

  // access token loops works fine,

  //   use it whenever u receive error 401 because it means that AT expired

  const newAccessTokenGenerated = response.data.token;

  return newAccessTokenGenerated;
}

// This part is for authenticating the menu and fetching the categories

async function authenticateMenu() {

  const url = CategoriesAuthUrl;

  let userToken = newUser.getToken();

  const authStr = "Bearer ".concat(userToken);

  const options = {
    method: "GET",
    headers: {
      Authorization: authStr,
    },
    url: url,
  };

  const response = await axios(options).catch(async (error) => {

    if (error.response.status === 401) {

      // should call the refreshToken to refresh the access and refresh token

      console.log("Error 401 unauthorized");


      const newUserToken = await updateAccessToken();

      userToken = newUserToken;
    }
    console.log(
      "😡 ~ file: menu.js:28 ~ authenticateMenu ~ Error getting categories from API call",
      error
    );
  });

  const fetchedCategories = response.data;

  console.log(
    "🚀 ~ file: menu.js:40 ~ authenticateMenu ~ fetchedCategories",
    fetchedCategories
  );

  return fetchedCategories;
}

//  Get Categories

export async function getCategories() {
  return authenticateMenu();
}

**In my HomeScreen I call the fetch categories like this**

 useEffect(() => {
    async function fetchCatHandler() {

      const categoriesFetched = await getCategories().catch((error) => {
        console.log(
          "🟥 ~ file: HomeScreen.js:63 ~ fetchCatHandler ~ error from fetching categories from Home screen",
          error
        );
      });

      setParsedCategories(categoriesFetched);
    }

    fetchCatHandler();

    async function getUserName() {
      setUserName(await newUser.getUserName());
    }

    getUserName();
  }, []);

// The code works perfectly fine until the access token is expired. Hence, whenever I receive error.response.status === 401 I call the function updateAccessToken which regenerates new access and refresh token and I save these in the user model

// when I fetch the categories it works fine up until the access token expires and I get the error [AxiosError: Request failed with status code 401].

// Any idea what am I missing/doing wrong??

   export async function updateAccessToken() {

  console.log("updateAccessToken called");

  const newGeneratedTokenAfterExpiration = await refreshTokenGenerator();
  

  newUser.setToken(newGeneratedTokenAfterExpiration);

  const userToken = newGeneratedTokenAfterExpiration;


  return userToken;
}

Once you've gotten an 401, the response is over. It doesn't change the response if you alter the token afterward. After getting a 401 and generating a new token, you should've sent a new request with the new token and return its response instead.

 async function authenticateMenu() { const url = CategoriesAuthUrl; let userToken = newUser.getToken(); const authStr = "Bearer ".concat(userToken); const options = { method: "GET", headers: { Authorization: authStr, }, url: url, }; const response = await axios(options).catch(async (error) => { if (error.response.status === 401) { // should call the refreshToken to refresh the access and refresh token console.log("Error 401 unauthorized"); const newUserToken = await updateAccessToken(); userToken = newUserToken; //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // >>>>> This doesn't effect the current req/resposnse. After reseting the token you should send another request, with the new token //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> } console.log( " ~ file: menu.js:28 ~ authenticateMenu ~ Error getting categories from API call", error ); }); const fetchedCategories = response.data; console.log( " ~ file: menu.js:40 ~ authenticateMenu ~ fetchedCategories", fetchedCategories ); return fetchedCategories; }

Regardless, you shouldn't refresh the token after it has already expired. It's not secure

Best of luck with your project:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM