Search code examples
reactjsamazon-cognitoaccess-token

How to refresh token using AWS coginto auth sdk


I am working on a feature of refreshing token once it's expire. I used amazon-cognito-auth-js to do the authorization and check here as an example, I implemented the below method to refresh token. however it doesn't work. Below is my code, and the session doesn't refresh as I expected. There is no synax error, just the auth token still expired. By the way, I use react.

import { CognitoAuth } from 'amazon-cognito-auth-js';
class Main extends Component {
   constructor() {
        this.state = {
            auth: ""
       }
   }
   componentDidMount() {
        //some logic to get the auth once user login success
        //here is the logic  to update the correct auth into the state
        this.setState({
            auth: auth
        })
    }
 //here is the method that check the token expire or not, if expire, refresh the token and update the state
   checkTokenExpiration (){
        let auth = this.state.auth;
        let user = auth.getCachedSession();
 //ideally, there shall have the logic to check the session is expired or not
// anyidea how to write it?
        auth.refreshSession(user.getRefreshToken().getToken());
        this.setState({
            auth:auth
        })
}

}

Solution

  • I close this question by myself. My solution is set up a timer in the frontend, once timer is over 1hr(for example). Just let user logout. Here is why you shall not refreshing token in the SPA. And here is the solution for dealing with refresh_token expire