Amazon Cognito SRP

Amazon Cognito SRP

Challenge

When you use Amazon Cognito as a User Pool, you set up app clients which will have access to this user pool. This way, the client can be authenticated and access the backend services that Cognito is protecting.

The most secure Auth Flows Configuration option is ALLOW_USER_SRP_AUTH, so you should enable SRP (secure remote password) protocol-based authentication.

However, in this case, the complexity of authentication becomes more complicated. You cannot use a username and password to authenticate your request if you want to call your backend services through the API.

Authentication

Initially, you must exchange your login and password for the JWT access token, id token, and refresh token. Then you can use the token to authenticate your request.

Username / Password – JWT exchange

Solution Description

Amazon Cognito SRP allows you to exchange your username and password for a token quickly and promptly call the backend service using any HTTP client (e.g., Postman).

Amazon Cognito SRP allows you to authenticate into Amazon Cognito by Username and Password through SRP-based authentication (the USER_SRP_AUTH authentication flow).Amazon Cognito SRP allows you to get the JWTaccess token, id token, and refresh token by Username and Password through SRP authentication.

Usage

const authResult: AuthResult = await amazonCognitoSrp.authenticate();

authResult output:

{
    accessToken: string;
    idToken: string;
    refreshToken: string;
}

JavaScript Examples

const { AmazonCognitoSrp } = require('amazon-cognito-srp');
    
const amazonCognitoSrp = new AmazonCognitoSrp({
    userPoolId: 'us-east-1_Gmmqbdhdd',
    clientId: '70681titoqu1dq7ho24j8h197o',
    username: 'test.email@gmail.com',
    password: 'test_password'
});
    
// If you run code in a sync function
amazonCognitoSrp.authenticate().then(result => {
    console.log(result)
});
    
// If you run code in a async function
(async () => {
    const result = await amazonCognitoSrp.authenticate();
    console.log(result)
})();

TypeScript Examples

import { AmazonCognitoSrp } from 'amazon-cognito-srp';
import { AuthResult, Options } from 'amazon-cognito-srp/lib/types';

const options: Options = {
    clientId: '70681titoqu1dq7ho24j8h197o',
    password: 'test_password',
    username: 'test.email@gmail.com',
    userPoolId: 'us-east-1_Gmmqbdhdd'
}

const amazonCognitoSrp = new AmazonCognitoSrp(options);

// If you run code in a sync function
amazonCognitoSrp.authenticate().then((authResult: AuthResult) => {
    console.log(authResult)
});

// If you run code in a async function
const authResult: AuthResult = await amazonCognitoSrp.authenticate();
console.log(authResult);

Reference

This tool is accessible via a link: https://www.npmjs.com/package/amazon-cognito-srp