or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mddevice-management.mdindex.mdmfa.mdsession-management.mdstorage.mduser-attributes.mduser-management.mduser-pool.md
tile.json

tessl/npm-amazon-cognito-identity-js

Amazon Cognito Identity Provider JavaScript SDK for user authentication and management

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/amazon-cognito-identity-js@6.3.x

To install, run

npx @tessl/cli install tessl/npm-amazon-cognito-identity-js@6.3.0

index.mddocs/

Amazon Cognito Identity JavaScript SDK

Amazon Cognito Identity JavaScript SDK provides comprehensive user authentication and management capabilities for AWS Cognito Identity Provider service. It offers complete authentication flows including user sign-up, sign-in, multi-factor authentication (MFA), password management, user attribute management, session handling, and device management. The SDK supports various authentication methods, automatic token refresh, and seamless integration across web applications, React Native apps, and Node.js environments.

Package Information

  • Package Name: amazon-cognito-identity-js
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install amazon-cognito-identity-js

Core Imports

import {
  CognitoUserPool,
  CognitoUser,
  AuthenticationDetails,
  AuthenticationHelper,
  CognitoUserSession,
  CognitoAccessToken,
  CognitoIdToken,
  CognitoRefreshToken,
  CognitoUserAttribute,
  CookieStorage,
  DateHelper,
  WordArray,
  appendToCognitoUserAgent
} from "amazon-cognito-identity-js";

For CommonJS:

const {
  CognitoUserPool,
  CognitoUser,
  AuthenticationDetails,
  AuthenticationHelper,
  CognitoUserSession,
  CognitoAccessToken,
  CognitoIdToken,
  CognitoRefreshToken,
  CognitoUserAttribute,
  CookieStorage,
  DateHelper,
  WordArray,
  appendToCognitoUserAgent
} = require("amazon-cognito-identity-js");

Basic Usage

import { CognitoUserPool, CognitoUser, AuthenticationDetails } from "amazon-cognito-identity-js";

// Initialize user pool
const userPool = new CognitoUserPool({
  UserPoolId: "us-east-1_XXXXXXXXX",
  ClientId: "your-client-id"
});

// Create user
const cognitoUser = new CognitoUser({
  Username: "testuser",
  Pool: userPool
});

// Sign in
const authDetails = new AuthenticationDetails({
  Username: "testuser",
  Password: "TempPassword123!"
});

cognitoUser.authenticateUser(authDetails, {
  onSuccess: (session) => {
    console.log("Authentication successful");
    console.log("Access Token:", session.getAccessToken().getJwtToken());
  },
  onFailure: (err) => {
    console.error("Authentication failed:", err);
  }
});

Architecture

Amazon Cognito Identity JavaScript SDK is built around several key components:

  • User Pool Management: CognitoUserPool handles user pool configuration and user creation
  • User Operations: CognitoUser provides all user-specific operations including authentication, attribute management, and device handling
  • Session Management: CognitoUserSession manages JWT tokens with automatic refresh capabilities
  • Authentication Flow: Support for SRP (Secure Remote Password), custom authentication, and various challenge flows
  • Storage Abstraction: Pluggable storage system supporting localStorage, cookies, and custom implementations
  • MFA Support: Built-in support for SMS MFA and TOTP (Time-based One-Time Password) authentication
  • Cross-Platform: Optimized for web browsers, React Native, and Node.js environments

Capabilities

User Pool Management

Core user pool operations including configuration, user registration, and pool-level management.

class CognitoUserPool {
  constructor(data: ICognitoUserPoolData, wrapRefreshSessionCallback?: any);
  getUserPoolId(): string;
  getUserPoolName(): string;
  getClientId(): string;
  signUp(
    username: string,
    password: string,
    userAttributes: CognitoUserAttribute[],
    validationData: CognitoUserAttribute[],
    callback: NodeCallback<Error, ISignUpResult>,
    clientMetadata?: ClientMetadata
  ): void;
  getCurrentUser(): CognitoUser | null;
}

interface ICognitoUserPoolData {
  UserPoolId: string;
  ClientId: string;
  endpoint?: string;
  Storage?: ICognitoStorage;
  AdvancedSecurityDataCollectionFlag?: boolean;
}

User Pool Management

User Authentication

Complete authentication system supporting multiple flows including SRP, custom authentication, and MFA challenges.

class AuthenticationDetails {
  constructor(data: IAuthenticationDetailsData);
  getUsername(): string;
  getPassword(): string;
  getValidationData(): any[];
  getClientMetadata(): object;
}

interface IAuthenticationDetailsData {
  Username: string;
  Password?: string;
  ValidationData?: { [key: string]: any };
  ClientMetadata?: ClientMetadata;
}

interface IAuthenticationCallback {
  onSuccess: (session: CognitoUserSession, userConfirmationNecessary?: boolean) => void;
  onFailure: (err: any) => void;
  newPasswordRequired?: (userAttributes: any, requiredAttributes: any) => void;
  mfaRequired?: (challengeName: ChallengeName, challengeParameters: any) => void;
  totpRequired?: (challengeName: ChallengeName, challengeParameters: any) => void;
  customChallenge?: (challengeParameters: any) => void;
  mfaSetup?: (challengeName: ChallengeName, challengeParameters: any) => void;
  selectMFAType?: (challengeName: ChallengeName, challengeParameters: any) => void;
}

User Authentication

User Management

Comprehensive user operations including registration, password management, and account control.

// Key user management methods from CognitoUser class
confirmRegistration(
  code: string,
  forceAliasCreation: boolean,
  callback: NodeCallback<any, any>,
  clientMetadata?: ClientMetadata
): void;

changePassword(
  oldPassword: string,
  newPassword: string,
  callback: NodeCallback<Error, 'SUCCESS'>,
  clientMetadata?: ClientMetadata
): void;

forgotPassword(
  callbacks: {
    onSuccess: (data: any) => void;
    onFailure: (err: Error) => void;
    inputVerificationCode?: (data: any) => void;
  },
  clientMetadata?: ClientMetadata
): void;

deleteUser(callback: NodeCallback<Error, string>): void;

User Management

Session Management

Token handling, validation, and automatic refresh capabilities for maintaining authenticated sessions.

class CognitoUserSession {
  constructor(data: ICognitoUserSessionData);
  getIdToken(): CognitoIdToken;
  getAccessToken(): CognitoAccessToken;
  getRefreshToken(): CognitoRefreshToken;
  isValid(): boolean;
}

interface ICognitoUserSessionData {
  IdToken: CognitoIdToken;
  AccessToken: CognitoAccessToken;
  RefreshToken?: CognitoRefreshToken;
}

// Token classes
class CognitoAccessToken {
  constructor(params: { AccessToken: string });
  getJwtToken(): string;
  getExpiration(): number;
  getIssuedAt(): number;
  decodePayload(): { [key: string]: any };
}

class CognitoIdToken {
  constructor(params: { IdToken: string });
  getJwtToken(): string;
  getExpiration(): number;
  getIssuedAt(): number;
  decodePayload(): { [key: string]: any };
}

Session Management

User Attributes

User attribute management including CRUD operations, verification, and attribute-specific workflows.

class CognitoUserAttribute {
  constructor(data: ICognitoUserAttributeData);
  Name: string;
  Value: string;
  getValue(): string;
  setValue(value: string): CognitoUserAttribute;
  getName(): string;
  setName(name: string): CognitoUserAttribute;
  toString(): string;
  toJSON(): object;
}

interface ICognitoUserAttributeData {
  Name: string;
  Value: string;
}

// Key attribute methods from CognitoUser class
getUserAttributes(callback: NodeCallback<Error, CognitoUserAttribute[]>): void;
updateAttributes(
  attributes: (CognitoUserAttribute | ICognitoUserAttributeData)[],
  callback: UpdateAttributesNodeCallback<Error, string, any>,
  clientMetadata?: ClientMetadata
): void;
deleteAttributes(attributeList: string[], callback: NodeCallback<Error, string>): void;
verifyAttribute(
  attributeName: string,
  confirmationCode: string,
  callbacks: {
    onSuccess: (success: string) => void;
    onFailure: (err: Error) => void;
  }
): void;

User Attributes

Multi-Factor Authentication

Complete MFA system supporting SMS and TOTP authentication methods with user preference management.

interface IMfaSettings {
  PreferredMfa: boolean;
  Enabled: boolean;
}

// Key MFA methods from CognitoUser class
setUserMfaPreference(
  smsMfaSettings: IMfaSettings | null,
  softwareTokenMfaSettings: IMfaSettings | null,
  callback: NodeCallback<Error, string>
): void;

associateSoftwareToken(callbacks: {
  associateSecretCode: (secretCode: string) => void;
  onFailure: (err: any) => void;
}): void;

verifySoftwareToken(
  totpCode: string,
  friendlyDeviceName: string,
  callbacks: {
    onSuccess: (session: CognitoUserSession) => void;
    onFailure: (err: Error) => void;
  }
): void;

sendMFACode(
  confirmationCode: string,
  callbacks: {
    onSuccess: (session: CognitoUserSession, userConfirmationNecessary?: boolean) => void;
    onFailure: (err: any) => void;
  },
  mfaType?: string,
  clientMetadata?: ClientMetadata
): void;

Multi-Factor Authentication

Device Management

Device tracking, remembering, and management for enhanced security and user experience.

// Key device methods from CognitoUser class
listDevices(
  limit: number,
  paginationToken: string | null,
  callbacks: {
    onSuccess: (data: any) => void;
    onFailure: (err: Error) => void;
  }
): void;

setDeviceStatusRemembered(callbacks: {
  onSuccess: (success: string) => void;
  onFailure: (err: any) => void;
}): void;

setDeviceStatusNotRemembered(callbacks: {
  onSuccess: (success: string) => void;
  onFailure: (err: any) => void;
}): void;

forgetDevice(callbacks: {
  onSuccess: (success: string) => void;
  onFailure: (err: Error) => void;
}): void;

forgetSpecificDevice(
  deviceKey: string,
  callbacks: {
    onSuccess: (success: string) => void;
    onFailure: (err: Error) => void;
  }
): void;

Device Management

Utility Classes and Functions

Additional utility classes and functions for specialized operations.

class DateHelper {
  /** Returns current time formatted as "ddd MMM D HH:mm:ss UTC YYYY" */
  getNowString(): string;
}

class WordArray {
  constructor(words?: string[], sigBytes?: number);
  /** Generates random word array */
  random(nBytes: number): WordArray;
  /** Returns hex string representation */  
  toString(): string;
}

/** Appends content to Cognito User Agent string */
function appendToCognitoUserAgent(content: string): void;

Note: AuthenticationHelper is exported for advanced SRP authentication scenarios but is typically handled internally by the SDK.

Storage Options

Flexible storage abstractions supporting various persistence mechanisms for session and configuration data.

interface ICognitoStorage {
  setItem(key: string, value: string): void;
  getItem(key: string): string | null;
  removeItem(key: string): void;
  clear(): void;
}

class CookieStorage implements ICognitoStorage {
  constructor(data?: ICookieStorageData);
  setItem(key: string, value: string): void;
  getItem(key: string): string;
  removeItem(key: string): void;
  clear(): void;
}

interface ICookieStorageData {
  domain?: string;
  path?: string;
  expires?: number;
  secure?: boolean;
  sameSite?: 'strict' | 'lax' | 'none';
}

Storage Options

Common Types

type NodeCallback<E, T> = (err?: E, result?: T) => void;
type UpdateAttributesNodeCallback<E, T, K> = (err?: E, result?: T, details?: K) => void;
type ClientMetadata = { [key: string]: string } | undefined;

type ChallengeName = 
  | 'CUSTOM_CHALLENGE'
  | 'MFA_SETUP'
  | 'NEW_PASSWORD_REQUIRED'
  | 'SELECT_MFA_TYPE'
  | 'SMS_MFA'
  | 'SOFTWARE_TOKEN_MFA';

interface CodeDeliveryDetails {
  AttributeName: string;
  DeliveryMedium: string;
  Destination: string;
}

interface ISignUpResult {
  user: CognitoUser;
  userConfirmed: boolean;
  userSub: string;
  codeDeliveryDetails: CodeDeliveryDetails;
}

interface MFAOption {
  DeliveryMedium: 'SMS' | 'EMAIL';
  AttributeName: string;
}

interface UserData {
  MFAOptions: MFAOption[];
  PreferredMfaSetting: string;
  UserAttributes: ICognitoUserAttributeData[];
  UserMFASettingList: string[];
  Username: string;
}

interface GetSessionOptions {
  clientMetadata: Record<string, string>;
}