Retrieving AWS Cognito Tokens Using TypeScript

Vinod Kumar
2 min readJun 1, 2023

--

Introduction

AWS Cognito is a powerful authentication and user management service provided by Amazon Web Services (AWS). It offers a range of features for managing user sign-up, sign-in, and token-based authentication. In this article, we will explore how to retrieve tokens from AWS Cognito using TypeScript. We will cover the necessary prerequisites and provide a TypeScript code snippet that demonstrates the token retrieval process.

Prerequisites

Before we dive into the code, make sure you have the following prerequisites in place

1. Create an App Client with a secret in your AWS Cognito User Pool.

2. Create a user with a password in the User Pool. After creation, confirmation status will be in “FORCE_CHANGE_PASSWORD”.

3. Set the user’s status to “CONFIRMED” using the below AWS CLI command.

aws cognito-idp admin-set-user-password \
--user-pool-id xxx \
--username xxx \
--password xxx \
--permanent

Retrieving Tokens using TypeScript

Now, let’s take a look at the TypeScript code snippet that retrieves tokens from AWS Cognito:

import crypto from 'crypto';
import {
CognitoIdentityProviderClient,
InitiateAuthCommand,
InitiateAuthCommandOutput,
} from '@aws-sdk/client-cognito-identity-provider';

const clientSecret = 'xxx';
const clientId = 'xxx';
const region = 'xxx';
const username = 'xxx';
const password = 'xxx';

function calculateSecretHash(
clientSecret: string,
username: string,
clientId: string
): string {
const message = username + clientId;
const hmac = crypto.createHmac('sha256', clientSecret);
hmac.update(message);
return hmac.digest('base64');
}

async function getToken(): Promise<string | undefined> {
const client = new CognitoIdentityProviderClient({ region });

try {
const secretHash = calculateSecretHash(clientSecret, username, clientId);
const initiateAuthCommand = new InitiateAuthCommand({
AuthFlow: 'USER_PASSWORD_AUTH',
AuthParameters: {
USERNAME: username,
PASSWORD: password,
SECRET_HASH: secretHash,
},
ClientId: clientId,
});

const authResult: InitiateAuthCommandOutput = await client.send(initiateAuthCommand);
if (authResult.AuthenticationResult?.AccessToken) {
return authResult.AuthenticationResult.AccessToken;
} else {
throw new Error('Failed to retrieve bearer token.');
}
} catch (error) {
throw error;
}
}

getToken();

Explanation

Let’s walk through the code step by step:

1. Import necessary modules and libraries: We import the required modules and libraries, including `crypto` for generating a secret hash and the AWS SDK’s `CognitoIdentityProviderClient` and `InitiateAuthCommand` for interacting with AWS Cognito.

2. Define the necessary variables: Set the values for `clientSecret`, `clientId`, `region`, `username`, and `password`. These values should correspond to your AWS Cognito setup.

3. Implement the `calculateSecretHash` function: This function calculates the secret hash required for the authentication process. It uses the client secret, username, and client ID to generate the hash using the `crypto` module.

4. Implement the `getToken` function: This function handles the token retrieval process. It creates a new instance of the `CognitoIdentityProviderClient` and initiates the authentication using the `InitiateAuthCommand`. The function checks if the authentication was successful and returns the access token if available.

5. Call the `getToken` function: Finally, we call the `getToken` function to retrieve the access token.

--

--

Vinod Kumar

Software Developer. Love to do backend of things. Enjoy acquiring new knowledge.