Reputation: 2196
I have an application that will be using cognito as an auth provider. I noticed that the id and access token both expire after an hour. This does not seem like a long time.
I've thought of two ways to manage the tokens but am unsure on which to choose/best practices.
Before every request to my backend I can check the expiration time on the token and if it is valid, use it, if it is invalid I can get a new token with the refresh token and use that.
Or
I can just refresh the token every request and use the new id/access token for the request.
How do most people manage these short lived tokens?
Upvotes: 4
Views: 1811
Reputation: 666
With cognito you get 3 kind of token all are stored in your storage. 1)Access-Token . (valid for 1 hour) 2)ID - Token . (valid for 1 hour) 3)Refresh Token . (valid for 1 month or 2 month please verify)
// For Web App
I have used AWS-Amplify for my web client.
In your landing page you should call Auth.currentSeesion();
When this will be called if the life( 1 hour) of access token and id token get exipers then this will look for refresh token and then the aws amplify will bring back access token and id token and store into storage.
link:https://aws-amplify.github.io/docs/js/authentication#token-refresh
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.1/umd/react-dom.production.min.js"></script>
useEffect(() => {
analytics.initialize();
// Update Authorization token
auth.currentSession()
.then(data => {
storage.saveDataInLocal(StorageKey.ACCESS_TOKEN, data.idToken.jwtToken);
const { email } = data.idToken.payload;
// checking if user was signed in by gmail
if(props.isGoogleSigned) {
// this code is required to auto login user if he closed the tab last time when he was logined
props.dispatch(sendGoogleSignInRequest(email));
}
props.dispatch(initialCall());
})
.catch(() => {
props.dispatch(initialCall());
});
// Validate user authentication status
auth.currentAuthenticatedUser()
.then(() => {
props.dispatch(fetchAppData());
}
)
.catch(() => {
if (storage.getDataFromLocal(StorageKey.USER_INFO)) {
props.dispatch(clearAppReducer());
storage.clearAllLocalData();
storage.clearAllSessionData();
props.history.push('/login');
}
});
}, []);
Upvotes: 2