Core user authentication flows including sign-up, sign-in, password management, and session handling for client-side applications using Amazon Cognito User Pools.
Register new users with email verification and custom attributes.
/**
* Register a new user in the user pool
* Initiates the user sign-up process with optional attributes and verification
*/
class SignUpCommand {
constructor(input: SignUpCommandInput);
}
interface SignUpCommandInput {
/** The ID of the client associated with the user pool */
ClientId: string;
/** The username for the user (can be email, phone, or custom username) */
Username: string;
/** The password for the user account */
Password: string;
/** An array of name-value pairs representing user attributes */
UserAttributes?: AttributeType[];
/** Validation data for the registration request */
ValidationData?: AttributeType[];
/** A map of client metadata to pass to Lambda triggers */
ClientMetadata?: Record<string, string>;
/** The Amazon Pinpoint analytics metadata for collecting metrics */
AnalyticsMetadata?: AnalyticsMetadataType;
/** Contextual data for advanced security features */
UserContextData?: UserContextDataType;
}
interface SignUpCommandOutput {
/** The UUID of the authenticated user */
UserSub: string;
/** Information about the code delivery details */
CodeDeliveryDetails?: CodeDeliveryDetailsType;
/** Confirmation status of the user account */
UserConfirmed: boolean;
}Usage Example:
import { CognitoIdentityProviderClient, SignUpCommand } from "@aws-sdk/client-cognito-identity-provider";
const client = new CognitoIdentityProviderClient({ region: "us-east-1" });
const signUpCommand = new SignUpCommand({
ClientId: "your-client-id",
Username: "user@example.com",
Password: "TempPassword123!",
UserAttributes: [
{ Name: "email", Value: "user@example.com" },
{ Name: "name", Value: "John Doe" },
{ Name: "phone_number", Value: "+1234567890" }
]
});
const signUpResult = await client.send(signUpCommand);
console.log("User registered:", signUpResult.UserSub);Confirm user registration using verification codes sent via email or SMS.
/**
* Confirm user registration using a verification code
* Completes the sign-up process initiated by SignUpCommand
*/
class ConfirmSignUpCommand {
constructor(input: ConfirmSignUpCommandInput);
}
interface ConfirmSignUpCommandInput {
/** The ID of the client associated with the user pool */
ClientId: string;
/** The username of the user to confirm */
Username: string;
/** The verification code received by the user */
ConfirmationCode: string;
/** Boolean to force alias creation */
ForceAliasCreation?: boolean;
/** Analytics metadata for Amazon Pinpoint */
AnalyticsMetadata?: AnalyticsMetadataType;
/** Contextual user data for advanced security */
UserContextData?: UserContextDataType;
/** Client metadata for Lambda triggers */
ClientMetadata?: Record<string, string>;
}
interface ConfirmSignUpCommandOutput {
/** Session information for further authentication steps */
Session?: string;
}Start the authentication process using various authentication flows.
/**
* Initiate authentication flow for a user
* Supports multiple authentication methods and flows
*/
class InitiateAuthCommand {
constructor(input: InitiateAuthCommandInput);
}
interface InitiateAuthCommandInput {
/** The authentication flow type */
AuthFlow: AuthFlowType;
/** Authentication parameters based on the selected flow */
AuthParameters?: Record<string, string>;
/** The ID of the client associated with the user pool */
ClientId: string;
/** Analytics metadata for Amazon Pinpoint */
AnalyticsMetadata?: AnalyticsMetadataType;
/** Contextual user data for advanced security */
UserContextData?: UserContextDataType;
/** Client metadata for Lambda triggers */
ClientMetadata?: Record<string, string>;
}
interface InitiateAuthCommandOutput {
/** The challenge name if authentication requires additional steps */
ChallengeName?: ChallengeNameType;
/** The session identifier for multi-step authentication */
Session?: string;
/** Challenge parameters for the next authentication step */
ChallengeParameters?: Record<string, string>;
/** Authentication result if authentication is complete */
AuthenticationResult?: AuthenticationResultType;
}
type AuthFlowType =
| "USER_SRP_AUTH" // Secure Remote Password (recommended)
| "USER_PASSWORD_AUTH" // Direct password authentication
| "CUSTOM_AUTH" // Custom authentication challenge
| "USER_AUTH" // Adaptive authentication
| "REFRESH_TOKEN_AUTH"; // Refresh token flow
interface AuthenticationResultType {
/** Access token for API calls */
AccessToken?: string;
/** Token expiration time in seconds */
ExpiresIn?: number;
/** Token type (typically "Bearer") */
TokenType?: string;
/** Refresh token for obtaining new access tokens */
RefreshToken?: string;
/** ID token containing user identity claims */
IdToken?: string;
/** New device metadata if device tracking is enabled */
NewDeviceMetadata?: NewDeviceMetadataType;
}Authentication Flow Examples:
// Secure Remote Password (SRP) Authentication - Recommended
const srpAuthCommand = new InitiateAuthCommand({
AuthFlow: "USER_SRP_AUTH",
ClientId: "your-client-id",
AuthParameters: {
USERNAME: "user@example.com"
}
});
// Direct Password Authentication - Less Secure
const passwordAuthCommand = new InitiateAuthCommand({
AuthFlow: "USER_PASSWORD_AUTH",
ClientId: "your-client-id",
AuthParameters: {
USERNAME: "user@example.com",
PASSWORD: "userPassword123!"
}
});
// Refresh Token Authentication
const refreshCommand = new InitiateAuthCommand({
AuthFlow: "REFRESH_TOKEN_AUTH",
ClientId: "your-client-id",
AuthParameters: {
REFRESH_TOKEN: "refresh-token-here"
}
});Respond to authentication challenges such as MFA, password reset, or custom challenges.
/**
* Respond to authentication challenges
* Handles MFA, password changes, and custom authentication challenges
*/
class RespondToAuthChallengeCommand {
constructor(input: RespondToAuthChallengeCommandInput);
}
interface RespondToAuthChallengeCommandInput {
/** The client ID for the user pool client */
ClientId: string;
/** The challenge name from InitiateAuth response */
ChallengeName: ChallengeNameType;
/** The session identifier from the previous authentication step */
Session?: string;
/** Challenge responses based on the challenge type */
ChallengeResponses?: Record<string, string>;
/** Analytics metadata for Amazon Pinpoint */
AnalyticsMetadata?: AnalyticsMetadataType;
/** Contextual user data for advanced security */
UserContextData?: UserContextDataType;
/** Client metadata for Lambda triggers */
ClientMetadata?: Record<string, string>;
}
type ChallengeNameType =
| "SMS_MFA" // SMS-based MFA challenge
| "SOFTWARE_TOKEN_MFA" // TOTP-based MFA challenge
| "SELECT_MFA_TYPE" // MFA method selection
| "MFA_SETUP" // MFA device setup
| "PASSWORD_VERIFIER" // SRP password verification
| "CUSTOM_CHALLENGE" // Custom Lambda challenge
| "DEVICE_SRP_AUTH" // Device-based SRP auth
| "DEVICE_PASSWORD_VERIFIER" // Device password verification
| "ADMIN_NO_SRP_AUTH" // Admin auth without SRP
| "NEW_PASSWORD_REQUIRED" // Temporary password change
| "SMS_OTP" // SMS one-time password
| "EMAIL_OTP"; // Email one-time passwordChallenge Response Examples:
// Respond to SMS MFA challenge
const mfaResponse = new RespondToAuthChallengeCommand({
ClientId: "your-client-id",
ChallengeName: "SMS_MFA",
Session: "session-from-initiate-auth",
ChallengeResponses: {
USERNAME: "user@example.com",
SMS_MFA_CODE: "123456"
}
});
// Respond to new password required challenge
const newPasswordResponse = new RespondToAuthChallengeCommand({
ClientId: "your-client-id",
ChallengeName: "NEW_PASSWORD_REQUIRED",
Session: "session-from-initiate-auth",
ChallengeResponses: {
USERNAME: "user@example.com",
NEW_PASSWORD: "NewSecurePassword123!"
}
});Handle forgotten passwords and password changes for authenticated users.
/**
* Initiate forgot password flow
* Sends password reset code to user's verified email or phone
*/
class ForgotPasswordCommand {
constructor(input: ForgotPasswordCommandInput);
}
interface ForgotPasswordCommandInput {
/** The client ID for the user pool client */
ClientId: string;
/** The username of the user requesting password reset */
Username: string;
/** Secret hash if client has a secret */
SecretHash?: string;
/** Contextual user data for advanced security */
UserContextData?: UserContextDataType;
/** Analytics metadata for Amazon Pinpoint */
AnalyticsMetadata?: AnalyticsMetadataType;
/** Client metadata for Lambda triggers */
ClientMetadata?: Record<string, string>;
}
/**
* Confirm forgot password with verification code
* Completes password reset process with new password
*/
class ConfirmForgotPasswordCommand {
constructor(input: ConfirmForgotPasswordCommandInput);
}
interface ConfirmForgotPasswordCommandInput {
/** The client ID for the user pool client */
ClientId: string;
/** The username of the user */
Username: string;
/** The verification code sent to user */
ConfirmationCode: string;
/** The new password for the user */
Password: string;
/** Secret hash if client has a secret */
SecretHash?: string;
/** Analytics metadata for Amazon Pinpoint */
AnalyticsMetadata?: AnalyticsMetadataType;
/** Contextual user data for advanced security */
UserContextData?: UserContextDataType;
/** Client metadata for Lambda triggers */
ClientMetadata?: Record<string, string>;
}
/**
* Change password for authenticated user
* Requires the user's current password and access token
*/
class ChangePasswordCommand {
constructor(input: ChangePasswordCommandInput);
}
interface ChangePasswordCommandInput {
/** The user's current password */
PreviousPassword: string;
/** The new password for the user */
ProposedPassword: string;
/** The access token for the authenticated user */
AccessToken: string;
}Manage user sessions, sign-out operations, and token refresh.
/**
* Sign out user from all devices globally
* Invalidates all refresh tokens and access tokens
*/
class GlobalSignOutCommand {
constructor(input: GlobalSignOutCommandInput);
}
interface GlobalSignOutCommandInput {
/** The access token for the authenticated user */
AccessToken: string;
}
/**
* Get current user information using access token
* Returns user attributes and metadata
*/
class GetUserCommand {
constructor(input: GetUserCommandInput);
}
interface GetUserCommandInput {
/** The access token for the authenticated user */
AccessToken: string;
}
interface GetUserCommandOutput {
/** The username of the user */
Username: string;
/** Array of user attributes */
UserAttributes: AttributeType[];
/** MFA options for the user */
MFAOptions?: MFAOptionType[];
/** Preferred MFA setting */
PreferredMfaSetting?: string;
/** List of enabled MFA options */
UserMFASettingList?: string[];
}Handle resending and managing verification codes for various operations.
/**
* Resend confirmation code for user registration
* Useful when the original code expires or is lost
*/
class ResendConfirmationCodeCommand {
constructor(input: ResendConfirmationCodeCommandInput);
}
interface ResendConfirmationCodeCommandInput {
/** The client ID for the user pool client */
ClientId: string;
/** The username to resend confirmation code for */
Username: string;
/** Secret hash if client has a secret */
SecretHash?: string;
/** Contextual user data for advanced security */
UserContextData?: UserContextDataType;
/** Analytics metadata for Amazon Pinpoint */
AnalyticsMetadata?: AnalyticsMetadataType;
/** Client metadata for Lambda triggers */
ClientMetadata?: Record<string, string>;
}
/**
* Get verification code for user attributes
* Initiates verification for email or phone number attributes
*/
class GetUserAttributeVerificationCodeCommand {
constructor(input: GetUserAttributeVerificationCodeCommandInput);
}
interface GetUserAttributeVerificationCodeCommandInput {
/** The access token for the authenticated user */
AccessToken: string;
/** The attribute name to verify (email, phone_number) */
AttributeName: string;
/** Client metadata for Lambda triggers */
ClientMetadata?: Record<string, string>;
}
/**
* Verify user attribute with confirmation code
* Completes attribute verification process
*/
class VerifyUserAttributeCommand {
constructor(input: VerifyUserAttributeCommandInput);
}
interface VerifyUserAttributeCommandInput {
/** The access token for the authenticated user */
AccessToken: string;
/** The attribute name being verified */
AttributeName: string;
/** The verification code received by the user */
Code: string;
}Complete Authentication Flow Example:
import {
CognitoIdentityProviderClient,
SignUpCommand,
ConfirmSignUpCommand,
InitiateAuthCommand,
RespondToAuthChallengeCommand
} from "@aws-sdk/client-cognito-identity-provider";
const client = new CognitoIdentityProviderClient({ region: "us-east-1" });
// 1. Sign up new user
const signUp = await client.send(new SignUpCommand({
ClientId: "your-client-id",
Username: "user@example.com",
Password: "TempPassword123!",
UserAttributes: [
{ Name: "email", Value: "user@example.com" }
]
}));
// 2. Confirm registration
const confirm = await client.send(new ConfirmSignUpCommand({
ClientId: "your-client-id",
Username: "user@example.com",
ConfirmationCode: "123456" // Code from email/SMS
}));
// 3. Authenticate user
const auth = await client.send(new InitiateAuthCommand({
AuthFlow: "USER_PASSWORD_AUTH",
ClientId: "your-client-id",
AuthParameters: {
USERNAME: "user@example.com",
PASSWORD: "TempPassword123!"
}
}));
// 4. Handle challenge if needed (e.g., MFA)
if (auth.ChallengeName === "SMS_MFA") {
const mfaResponse = await client.send(new RespondToAuthChallengeCommand({
ClientId: "your-client-id",
ChallengeName: "SMS_MFA",
Session: auth.Session,
ChallengeResponses: {
USERNAME: "user@example.com",
SMS_MFA_CODE: "654321" // Code from SMS
}
}));
console.log("Access token:", mfaResponse.AuthenticationResult?.AccessToken);
}Commands for users to manage their own accounts and attributes.
/**
* Delete user account
* Allow authenticated users to delete their own account
*/
class DeleteUserCommand {
constructor(input: DeleteUserCommandInput);
}
interface DeleteUserCommandInput {
/** Access token for authenticated user */
AccessToken: string;
}
/**
* Delete user attributes
* Remove specific attributes from user profile
*/
class DeleteUserAttributesCommand {
constructor(input: DeleteUserAttributesCommandInput);
}
interface DeleteUserAttributesCommandInput {
/** Access token for authenticated user */
AccessToken: string;
/** Names of attributes to delete */
UserAttributeNames: string[];
}
/**
* Update user attributes
* Modify or add user profile attributes
*/
class UpdateUserAttributesCommand {
constructor(input: UpdateUserAttributesCommandInput);
}
interface UpdateUserAttributesCommandInput {
/** Access token for authenticated user */
AccessToken: string;
/** Attributes to update */
UserAttributes: AttributeType[];
/** Client metadata for Lambda triggers */
ClientMetadata?: Record<string, string>;
}
/**
* Set user settings
* Configure user-level MFA and other preferences
*/
class SetUserSettingsCommand {
constructor(input: SetUserSettingsCommandInput);
}
interface SetUserSettingsCommandInput {
/** Access token for authenticated user */
AccessToken: string;
/** MFA options to set for the user */
MFAOptions: MFAOptionType[];
}
/**
* Update authentication event feedback
* Provide feedback on authentication events for risk analysis
*/
class UpdateAuthEventFeedbackCommand {
constructor(input: UpdateAuthEventFeedbackCommandInput);
}
interface UpdateAuthEventFeedbackCommandInput {
/** Access token for authenticated user */
AccessToken: string;
/** Event ID to provide feedback for */
EventId: string;
/** Feedback value (Valid or Invalid) */
FeedbackValue: FeedbackValueType;
}