Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Cognito - Programatically get refresh token expiry

Refresh token returned from Cognito is not a JWT token , hence cannot be decoded. Is there a way to get the refresh token expiry or it needs to be maintained at application level.

like image 661
user2160919 Avatar asked Apr 18 '26 04:04

user2160919


2 Answers

There is no way to decode a refresh token. If you know the expiration time set in cognito for refresh tokens you can store the time it was generated and calculate based on that.

like image 128
Ninad Gaikwad Avatar answered Apr 22 '26 05:04

Ninad Gaikwad


just to elaborate on the accepted answer, as I had the same question.

  • jwt.org cannot decode the refresh token from aws, as it is encrypted

My way around it, is as follows:

  • the id token carries "auth_time" (see https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html)
  • on login (you could technically do it on refresh as well), I look at that value and add expiration duration to that for a rough estimate
  • how to get the expiration duration programmatically? There are probably easier ways to do it, but the sdk-v3 command that worked for me was the 'DescribeUserPoolClientCommand' (https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-cognito-identity-provider/classes/describeuserpoolclientcommand.html)

pseudo code in typescript (used in nodejs backend code) looks something like this:

import { CognitoIdentityProviderClient, DescribeUserPoolClientCommand, DescribeUserPoolClientCommandInput} from "@aws-sdk/client-cognito-identity-provider"
import get from 'lodash/get'

const client = new CognitoIdentityProviderClient({ region: [yourRegion] }) 
const input = {
    UserPoolId: [yourUserPoolId],
    ClientId: [yourWebClientId],
} as DescribeUserPoolClientCommandInput
const command = new DescribeUserPoolClientCommand(input)

const response = await client.send(command)
const refreshTokenValidityUnits = get(
    response,
    "UserPoolClient.TokenValidityUnits.RefreshToken"
)
const refreshTokenValidity = get(
    response,
    "UserPoolClient.RefreshTokenValidity"
)
// result: "days" and "30" for example

This is obviously not complete enough to get the exact values, but enough to get anyone started who, like me, might not be as familiar with the aws-sdk yet.

like image 34
Sven Avatar answered Apr 22 '26 06:04

Sven



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!