Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle with token expiration on Cognito

Tags:

I am developing an application that uses AWS Cognito as the Identity Provider. So the user authenticate on AWS Cognito Pool and get the Access Token, Access ID and Refresh token. Then the user can make backend requests to my app. I get the Access Token validate it, get the user profile on Cognito AWS and authorize the request.

The problem is that after the Access token has expired, and the client send the expired token to the backend, the backend app get an error (token experied or not authorized).

How can I make this workflow works?

I was thinking in send to the client a message that the token has expired, and the the cliente refresh it against the Cognito Pool. Is it the correct approach?

like image 579
p.magalhaes Avatar asked Oct 11 '17 11:10

p.magalhaes


People also ask

How do I handle expired access tokens?

For example, once an access token expires, the client application could prompt the user to log in again to get a new access token. Alternatively, the authorization server could issue a refresh token to the client application that lets it replace an expired access token with a new one.

How do Cognito tokens expire?

By default, Amazon Cognito refresh tokens expire 30 days after a user signs in to a user pool. When you create an app, you can set the app's refresh token expiration to any value between 60 minutes and 10 years.

How do I know if my Cognito access token is expired?

You can decode the JWT token and also cache this expiry along with the token. Every time the cache for the tokens is accessed, also check the current time against the cached expiry time. If expired, use the Refresh token to obtain the latest Access and ID token and cache the tokens and expiry again.

What happens when access token expires?

When the access token expires, the application will be forced to make the user sign in again, so that you as the service know the user is continually involved in re-authorizing the application.


1 Answers

When you get the Access Token, ID and Refresh token from Cognito User Pools, you must cache it locally. The Access and the ID token are valid for 1 hour and should be reused as much as possible within that time period.

These tokens are JWT tokens and hold the expiry time within themselves. You can decode the JWT token and also cache this expiry along with the token. Every time the cache for the tokens is accessed, also check the current time against the cached expiry time. If expired, use the Refresh token to obtain the latest Access and ID token and cache the tokens and expiry again.

If you use one of our high level SDKs for Android, iOS of JavaScript, the SDK manages all of this for you.

like image 152
Chetan Mehta Avatar answered Oct 04 '22 14:10

Chetan Mehta