Published on

Authenticate with Cognito using the AWS SDK

Authors
  • avatar
    Name
    Andreas Caldewei
    Twitter
Docker logo

This article presents an alternative by using the AWS SDK instead of AWS Amplify for authentication with AWS Cognito.

Overview

What is CognitoIdentityServiceProvider?

CognitoIdentityServiceProvider is a class in the AWS SDK that allows you to integrate your web or mobile application with Amazon Cognito. It provides a set of functions that you can use to sign up and sign in.

Sign Up

import { CognitoIdentityServiceProvider } from 'aws-sdk'

const cognitoIdentityServiceProvider = new CognitoIdentityServiceProvider()

const signUpResponse = await cognitoIdentityServiceProvider
  .signUp({
    ClientId: 'YOUR_CLIENT_ID',
    Password: 'YOUR_PASSWORD',
    Username: 'YOUR_USERNAME',
    UserAttributes: [
      {
        Name: 'email',
        Value: 'YOUR_EMAIL',
      },
    ],
  })
  .promise()

When signUp is called, it will send a request to the Cognito service to create a new user with the specified username, password, and email address. The ClientId field specifies the client ID of the app that is attempting to sign up the user. The UserAttributes field is an array of attribute objects that specify additional user attributes, such as the user's email address in this case.

Sign In

import { CognitoIdentityServiceProvider } from 'aws-sdk'

const cognitoIdentityServiceProvider = new CognitoIdentityServiceProvider()

const loginResponse = await cognitoIdentityServiceProvider
  .initiateAuth({
    AuthFlow: 'USER_PASSWORD_AUTH',
    ClientId: 'YOUR_CLIENT_ID',
    AuthParameters: {
      USERNAME: 'YOUR_USERNAME',
      PASSWORD: 'YOUR_PASSWORD',
    },
  })
  .promise()

When initiateAuth is called, it will send a request to the Cognito service to authenticate the user with the specified username and password. The AuthFlow field specifies the authentication flow that is being used, which in this case is USER_PASSWORD_AUTH for a basic username and password authentication flow. The ClientId field specifies the client ID of the app that is attempting to log in the user.

The response contains a AccessToken and IdToken which can be used further authorizes with other AWS Services.

Setting Credentials for AWS SDK

import { CognitoIdentityServiceProvider, CognitoIdentityCredentials, config } from "aws-sdk";

...

config.credentials = new CognitoIdentityCredentials({
 IdentityPoolId: 'YOUR_IDENTITY_POOL_ID',
  Logins: {
    'cognito-idp.REGION.amazonaws.com/YOUR_USER_POOL_ID': loginResponse.AuthenticationResult.IdToken,
  },
});

The IdToken can be used to create CognitoIdentityCredentials that can be set as default credentials for the SDK. This means that any AWS service clients that are created subsequently will use these credentials by default when making requests.