Donjack
Donjack

Reputation: 33

Best practice/method to refresh token with AWS Cognito and AXIOS in ReactJS

I am doing the below in my App.JS but it is not refreshing the token in the other components. Can some one suggest what would be the best way to check if the token is valid or refresh it from all the components before the AXIOS call is made. If you could provide a link to any example it would be great.

import { Auth } from "aws-amplify";
import setAuthorizationToken from './components/utility/SetAuthorizationToken';


async componentWillMount() {    
    try {            
       console.log("Im am in componentWillMount() in App.js");
       await Auth.currentSession().then(data => {
        this.setAuthStatus(true);
      }).catch(err => {
        this.setAuthStatus(false)
        });
      await Auth.currentAuthenticatedUser().then(user => {
        this.setUser(user);
        setAuthorizationToken(user.signInUserSession.idToken.jwtToken);
      });     
    } catch(error) {
      if (error !== 'No current user') {
        console.log(error);
      }
    }
    this.setState({ isAuthenticating: false });  
  }

SetAuthorizationToken.js

import axios from 'axios';

export default function SetAuthorizationToken(token) {
    if(token){
        axios.defaults.headers.common['Authorization'] = token;       
    }else{
        delete axios.defaults.headers.common['Authorization'];
    }
}

Upvotes: 2

Views: 3883

Answers (1)

Domino987
Domino987

Reputation: 8804

You do not have to track the JWT token or user or refresh it by yourself with cognito.

For the axios call just use await Auth.currentSession() before the axios call and inject the token directly from the callback into your axios call. currentSession will only return a valid token and will try to refresh it, if it is expeired.

That way, you can rely on AWS to always provide you with a valid token without tracking it yourself.

You also do not have to save the user since you can access him anywhere you need it with the currentAuthenticatedUser call.

Upvotes: 11

Related Questions