Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically refresh Cognito Token in a page

I use AWS Cognito service for authentication. In my Angular 7 app, I use Amplify Auth to guard my pages.

If user navigates between different pages, Amplify will automatically handle the token refresh and they will not see token expirations.

If user stay in one page for long time, then the token will not be refreshed and eventually user will see expired token and will got 403 for web service call.

Any good solution to refresh access/id tokens if user stay in the same page for long time?

like image 547
user2777473 Avatar asked Oct 27 '25 06:10

user2777473


1 Answers

Probably two ways :

  1. Use Auth.currentSession() to get current valid token or get the new if current has expired. Amplify will handle it
  2. As a fallback, use some interval job to refresh tokens on demand every x minutes, maybe 10 min. This is required when you have a long running process like uploading a very large video which will take more than hour (maybe due to slow network) then your token will expire during the upload and amplify will not update automatically for you. In this case, this strategy will work. Keep updating your tokens on some interval. How to refresh on demand is not mentioned in docs so here it is.
import { Auth } from 'aws-amplify';

try {
  const cognitoUser = await Auth.currentAuthenticatedUser();
  const currentSession = await Auth.currentSession();
  cognitoUser.refreshSession(currentSession.refreshToken, (err, session) => {
    console.log('session', err, session);
    const { idToken, refreshToken, accessToken } = session;
    // do whatever you want to do now :)
  });
} catch (e) {
  console.log('Unable to refresh Token', e);
}

more here : https://github.com/aws-amplify/amplify-js/issues/2560

like image 180
manishm Avatar answered Oct 29 '25 08:10

manishm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!