Complete authentication system supporting multiple flows including SRP (Secure Remote Password), custom authentication, and MFA challenges.
Contains authentication data required for user sign-in operations.
/**
* Contains authentication data for user sign-in
* @param data - Authentication details including username, password, and metadata
*/
class AuthenticationDetails {
constructor(data: IAuthenticationDetailsData);
/** Returns the username for authentication */
getUsername(): string;
/** Returns the password for authentication */
getPassword(): string;
/** Returns validation data as an array */
getValidationData(): any[];
/** Returns client metadata object */
getClientMetadata(): object;
/** Returns authentication parameters for custom authentication flows */
getAuthParameters(): object;
}
interface IAuthenticationDetailsData {
/** Username for authentication */
Username: string;
/** Password for authentication (optional for some flows) */
Password?: string;
/** Additional validation data for custom authentication */
ValidationData?: { [key: string]: any };
/** Client metadata passed to Lambda triggers */
ClientMetadata?: ClientMetadata;
}Core authentication methods available on the CognitoUser class.
/**
* Main authentication method using SRP (Secure Remote Password) protocol
* @param authenticationDetails - Authentication credentials and metadata
* @param callbacks - Callback handlers for different authentication outcomes
*/
authenticateUser(
authenticationDetails: AuthenticationDetails,
callbacks: IAuthenticationCallback
): void;
/**
* Initiates custom authentication flow
* @param authenticationDetails - Authentication credentials and metadata
* @param callbacks - Callback handlers for different authentication outcomes
*/
initiateAuth(
authenticationDetails: AuthenticationDetails,
callbacks: IAuthenticationCallback
): void;
/**
* Completes new password required challenge
* @param newPassword - The new password to set
* @param requiredAttributeData - Required user attributes that need to be set
* @param callbacks - Callback handlers for authentication outcomes
* @param clientMetadata - Optional client metadata for Lambda triggers
*/
completeNewPasswordChallenge(
newPassword: string,
requiredAttributeData: any,
callbacks: IAuthenticationCallback,
clientMetadata?: ClientMetadata
): void;
/**
* Sends answer for custom challenge
* @param answerChallenge - The challenge answer
* @param callbacks - Callback handlers for authentication outcomes
* @param clientMetadata - Optional client metadata for Lambda triggers
*/
sendCustomChallengeAnswer(
answerChallenge: any,
callbacks: IAuthenticationCallback,
clientMetadata?: ClientMetadata
): void;
/**
* Sends MFA code for verification
* @param confirmationCode - The MFA code from SMS or TOTP device
* @param callbacks - Success/failure callback handlers
* @param mfaType - Optional MFA type ('SMS_MFA' or 'SOFTWARE_TOKEN_MFA')
* @param clientMetadata - Optional client metadata for Lambda triggers
*/
sendMFACode(
confirmationCode: string,
callbacks: {
onSuccess: (session: CognitoUserSession, userConfirmationNecessary?: boolean) => void;
onFailure: (err: any) => void;
},
mfaType?: string,
clientMetadata?: ClientMetadata
): void;
/**
* Sends MFA type selection answer
* @param answerChallenge - Selected MFA type ('SMS' or 'SOFTWARE_TOKEN')
* @param callbacks - Callback handlers with additional MFA flow options
*/
sendMFASelectionAnswer(
answerChallenge: string,
callbacks: {
onSuccess: (session: CognitoUserSession) => void;
onFailure: (err: any) => void;
mfaRequired?: (challengeName: ChallengeName, challengeParameters: any) => void;
totpRequired?: (challengeName: ChallengeName, challengeParameters: any) => void;
}
): void;Comprehensive callback interface handling all authentication flow outcomes.
interface IAuthenticationCallback {
/** Called when authentication succeeds */
onSuccess: (session: CognitoUserSession, userConfirmationNecessary?: boolean) => void;
/** Called when authentication fails */
onFailure: (err: any) => void;
/** Called when user must set a new password (first-time login) */
newPasswordRequired?: (userAttributes: any, requiredAttributes: any) => void;
/** Called when MFA is required (SMS or TOTP) */
mfaRequired?: (challengeName: ChallengeName, challengeParameters: any) => void;
/** Called when TOTP MFA is specifically required */
totpRequired?: (challengeName: ChallengeName, challengeParameters: any) => void;
/** Called when custom challenge is presented */
customChallenge?: (challengeParameters: any) => void;
/** Called when MFA setup is required (first-time MFA) */
mfaSetup?: (challengeName: ChallengeName, challengeParameters: any) => void;
/** Called when user must select MFA type */
selectMFAType?: (challengeName: ChallengeName, challengeParameters: any) => void;
}
type ChallengeName =
| 'CUSTOM_CHALLENGE'
| 'MFA_SETUP'
| 'NEW_PASSWORD_REQUIRED'
| 'SELECT_MFA_TYPE'
| 'SMS_MFA'
| 'SOFTWARE_TOKEN_MFA';Usage Examples:
import { CognitoUser, AuthenticationDetails } from "amazon-cognito-identity-js";
// Basic authentication
const authDetails = new AuthenticationDetails({
Username: "johndoe",
Password: "MyPassword123!"
});
cognitoUser.authenticateUser(authDetails, {
onSuccess: (session) => {
console.log("Authentication successful");
console.log("Access Token:", session.getAccessToken().getJwtToken());
console.log("ID Token:", session.getIdToken().getJwtToken());
},
onFailure: (err) => {
console.error("Authentication failed:", err.message);
},
newPasswordRequired: (userAttributes, requiredAttributes) => {
console.log("New password required");
console.log("User attributes:", userAttributes);
console.log("Required attributes:", requiredAttributes);
// Complete new password challenge
const newPassword = "NewSecurePassword123!";
const requiredAttributeData = {
email: "user@example.com" // if email is required
};
cognitoUser.completeNewPasswordChallenge(
newPassword,
requiredAttributeData,
{
onSuccess: (session) => {
console.log("New password set successfully");
},
onFailure: (err) => {
console.error("New password failed:", err);
}
}
);
},
mfaRequired: (challengeName, challengeParameters) => {
console.log("MFA required:", challengeName);
const mfaCode = prompt("Enter MFA code:");
cognitoUser.sendMFACode(mfaCode, {
onSuccess: (session) => {
console.log("MFA authentication successful");
},
onFailure: (err) => {
console.error("MFA failed:", err);
}
});
}
});The SDK supports different authentication flow types that can be set on the user:
/**
* Gets the current authentication flow type
* @returns Current flow type string
*/
getAuthenticationFlowType(): string;
/**
* Sets the authentication flow type
* @param authenticationFlowType - Flow type ('USER_SRP_AUTH', 'CUSTOM_AUTH', etc.)
* @returns The set authentication flow type
*/
setAuthenticationFlowType(authenticationFlowType: string): string;Flow Types:
'USER_SRP_AUTH' - Secure Remote Password (default)'CUSTOM_AUTH' - Custom authentication challenge'USER_PASSWORD_AUTH' - Direct password authentication (must be enabled in user pool)Getting and refreshing user sessions:
/**
* Gets the current session, refreshing if necessary
* @param callback - Callback with session result
* @param options - Optional session options including client metadata
*/
getSession(
callback:
| ((error: Error, session: null) => void)
| ((error: null, session: CognitoUserSession) => void),
options?: GetSessionOptions
): void;
/**
* Refreshes the user session using refresh token
* @param refreshToken - Valid refresh token
* @param callback - Callback with refreshed session result
* @param clientMetadata - Optional client metadata for Lambda triggers
*/
refreshSession(
refreshToken: CognitoRefreshToken,
callback: NodeCallback<any, any>,
clientMetadata?: ClientMetadata
): void;
interface GetSessionOptions {
clientMetadata: Record<string, string>;
}Usage Example:
// Get current session
cognitoUser.getSession((err, session) => {
if (err) {
console.error("Session error:", err);
return;
}
if (session && session.isValid()) {
console.log("Valid session found");
console.log("Access token:", session.getAccessToken().getJwtToken());
} else {
console.log("No valid session");
}
});
// Refresh session
const refreshToken = session.getRefreshToken();
cognitoUser.refreshSession(refreshToken, (err, newSession) => {
if (err) {
console.error("Refresh failed:", err);
return;
}
console.log("Session refreshed successfully");
});Signing out users locally or globally:
/**
* Signs out the user locally (clears local session)
* @param callback - Optional callback when sign out completes
*/
signOut(callback?: () => void): void;
/**
* Signs out the user globally (invalidates all sessions across devices)
* @param callbacks - Success/failure callbacks
*/
globalSignOut(callbacks: {
onSuccess: (msg: string) => void;
onFailure: (err: Error) => void;
}): void;Usage Example:
// Local sign out
cognitoUser.signOut(() => {
console.log("User signed out locally");
});
// Global sign out
cognitoUser.globalSignOut({
onSuccess: (msg) => {
console.log("Global sign out successful:", msg);
},
onFailure: (err) => {
console.error("Global sign out failed:", err);
}
});