Amazon Cognito Identity Provider examples using SDK for JavaScript (v3) - Amazon SDK for JavaScript
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

The Amazon SDK for JavaScript V3 API Reference Guide describes in detail all the API operations for the Amazon SDK for JavaScript version 3 (V3).

Amazon Cognito Identity Provider examples using SDK for JavaScript (v3)

The following code examples show you how to perform actions and implement common scenarios by using the Amazon SDK for JavaScript (v3) with Amazon Cognito Identity Provider.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Get started

The following code examples show how to get started using Amazon Cognito.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import { paginateListUserPools, CognitoIdentityProviderClient, } from "@aws-sdk/client-cognito-identity-provider"; const client = new CognitoIdentityProviderClient({}); export const helloCognito = async () => { const paginator = paginateListUserPools({ client }, {}); const userPoolNames = []; for await (const page of paginator) { const names = page.UserPools.map((pool) => pool.Name); userPoolNames.push(...names); } console.log("User pool names: "); console.log(userPoolNames.join("\n")); return userPoolNames; };
  • For API details, see ListUserPools in Amazon SDK for JavaScript API Reference.

Actions

The following code example shows how to use AdminGetUser.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const adminGetUser = ({ userPoolId, username }) => { const client = new CognitoIdentityProviderClient({}); const command = new AdminGetUserCommand({ UserPoolId: userPoolId, Username: username, }); return client.send(command); };
  • For API details, see AdminGetUser in Amazon SDK for JavaScript API Reference.

The following code example shows how to use AdminInitiateAuth.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const adminInitiateAuth = ({ clientId, userPoolId, username, password }) => { const client = new CognitoIdentityProviderClient({}); const command = new AdminInitiateAuthCommand({ ClientId: clientId, UserPoolId: userPoolId, AuthFlow: AuthFlowType.ADMIN_USER_PASSWORD_AUTH, AuthParameters: { USERNAME: username, PASSWORD: password }, }); return client.send(command); };

The following code example shows how to use AdminRespondToAuthChallenge.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const adminRespondToAuthChallenge = ({ userPoolId, clientId, username, totp, session, }) => { const client = new CognitoIdentityProviderClient({}); const command = new AdminRespondToAuthChallengeCommand({ ChallengeName: ChallengeNameType.SOFTWARE_TOKEN_MFA, ChallengeResponses: { SOFTWARE_TOKEN_MFA_CODE: totp, USERNAME: username, }, ClientId: clientId, UserPoolId: userPoolId, Session: session, }); return client.send(command); };

The following code example shows how to use AssociateSoftwareToken.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const associateSoftwareToken = (session) => { const client = new CognitoIdentityProviderClient({}); const command = new AssociateSoftwareTokenCommand({ Session: session, }); return client.send(command); };

The following code example shows how to use ConfirmDevice.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const confirmDevice = ({ deviceKey, accessToken, passwordVerifier, salt }) => { const client = new CognitoIdentityProviderClient({}); const command = new ConfirmDeviceCommand({ DeviceKey: deviceKey, AccessToken: accessToken, DeviceSecretVerifierConfig: { PasswordVerifier: passwordVerifier, Salt: salt, }, }); return client.send(command); };
  • For API details, see ConfirmDevice in Amazon SDK for JavaScript API Reference.

The following code example shows how to use ConfirmSignUp.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const confirmSignUp = ({ clientId, username, code }) => { const client = new CognitoIdentityProviderClient({}); const command = new ConfirmSignUpCommand({ ClientId: clientId, Username: username, ConfirmationCode: code, }); return client.send(command); };
  • For API details, see ConfirmSignUp in Amazon SDK for JavaScript API Reference.

The following code example shows how to use InitiateAuth.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const initiateAuth = ({ username, password, clientId }) => { const client = new CognitoIdentityProviderClient({}); const command = new InitiateAuthCommand({ AuthFlow: AuthFlowType.USER_PASSWORD_AUTH, AuthParameters: { USERNAME: username, PASSWORD: password, }, ClientId: clientId, }); return client.send(command); };
  • For API details, see InitiateAuth in Amazon SDK for JavaScript API Reference.

The following code example shows how to use ListUsers.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const listUsers = ({ userPoolId }) => { const client = new CognitoIdentityProviderClient({}); const command = new ListUsersCommand({ UserPoolId: userPoolId, }); return client.send(command); };
  • For API details, see ListUsers in Amazon SDK for JavaScript API Reference.

The following code example shows how to use ResendConfirmationCode.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const resendConfirmationCode = ({ clientId, username }) => { const client = new CognitoIdentityProviderClient({}); const command = new ResendConfirmationCodeCommand({ ClientId: clientId, Username: username, }); return client.send(command); };

The following code example shows how to use RespondToAuthChallenge.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const respondToAuthChallenge = ({ clientId, username, session, userPoolId, code, }) => { const client = new CognitoIdentityProviderClient({}); const command = new RespondToAuthChallengeCommand({ ChallengeName: ChallengeNameType.SOFTWARE_TOKEN_MFA, ChallengeResponses: { SOFTWARE_TOKEN_MFA_CODE: code, USERNAME: username, }, ClientId: clientId, UserPoolId: userPoolId, Session: session, }); return client.send(command); };

The following code example shows how to use SignUp.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const signUp = ({ clientId, username, password, email }) => { const client = new CognitoIdentityProviderClient({}); const command = new SignUpCommand({ ClientId: clientId, Username: username, Password: password, UserAttributes: [{ Name: "email", Value: email }], }); return client.send(command); };
  • For API details, see SignUp in Amazon SDK for JavaScript API Reference.

The following code example shows how to use VerifySoftwareToken.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

const verifySoftwareToken = (totp) => { const client = new CognitoIdentityProviderClient({}); // The 'Session' is provided in the response to 'AssociateSoftwareToken'. const session = process.env.SESSION; if (!session) { throw new Error( "Missing a valid Session. Did you run 'admin-initiate-auth'?", ); } const command = new VerifySoftwareTokenCommand({ Session: session, UserCode: totp, }); return client.send(command); };

Scenarios

The following code example shows how to:

  • Sign up and confirm a user with a username, password, and email address.

  • Set up multi-factor authentication by associating an MFA application with the user.

  • Sign in by using a password and an MFA code.

SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

For the best experience, clone the GitHub repository and run this example. The following code represents a sample of the full example application.

import { log } from "@aws-doc-sdk-examples/lib/utils/util-log.js"; import { signUp } from "../../../actions/sign-up.js"; import { FILE_USER_POOLS } from "./constants.js"; import { getSecondValuesFromEntries } from "@aws-doc-sdk-examples/lib/utils/util-csv.js"; const validateClient = (clientId) => { if (!clientId) { throw new Error( `App client id is missing. Did you run 'create-user-pool'?`, ); } }; const validateUser = (username, password, email) => { if (!(username && password && email)) { throw new Error( `Username, password, and email must be provided as arguments to the 'sign-up' command.`, ); } }; const signUpHandler = async (commands) => { const [_, username, password, email] = commands; try { validateUser(username, password, email); /** * @type {string[]} */ const values = getSecondValuesFromEntries(FILE_USER_POOLS); const clientId = values[0]; validateClient(clientId); log(`Signing up.`); await signUp({ clientId, username, password, email }); log(`Signed up. A confirmation email has been sent to: ${email}.`); log(`Run 'confirm-sign-up ${username} <code>' to confirm your account.`); } catch (err) { log(err); } }; export { signUpHandler }; const signUp = ({ clientId, username, password, email }) => { const client = new CognitoIdentityProviderClient({}); const command = new SignUpCommand({ ClientId: clientId, Username: username, Password: password, UserAttributes: [{ Name: "email", Value: email }], }); return client.send(command); }; import { log } from "@aws-doc-sdk-examples/lib/utils/util-log.js"; import { confirmSignUp } from "../../../actions/confirm-sign-up.js"; import { FILE_USER_POOLS } from "./constants.js"; import { getSecondValuesFromEntries } from "@aws-doc-sdk-examples/lib/utils/util-csv.js"; const validateClient = (clientId) => { if (!clientId) { throw new Error( `App client id is missing. Did you run 'create-user-pool'?`, ); } }; const validateUser = (username) => { if (!username) { throw new Error( `Username name is missing. It must be provided as an argument to the 'confirm-sign-up' command.`, ); } }; const validateCode = (code) => { if (!code) { throw new Error( `Verification code is missing. It must be provided as an argument to the 'confirm-sign-up' command.`, ); } }; const confirmSignUpHandler = async (commands) => { const [_, username, code] = commands; try { validateUser(username); validateCode(code); /** * @type {string[]} */ const values = getSecondValuesFromEntries(FILE_USER_POOLS); const clientId = values[0]; validateClient(clientId); log(`Confirming user.`); await confirmSignUp({ clientId, username, code }); log( `User confirmed. Run 'admin-initiate-auth ${username} <password>' to sign in.`, ); } catch (err) { log(err); } }; export { confirmSignUpHandler }; const confirmSignUp = ({ clientId, username, code }) => { const client = new CognitoIdentityProviderClient({}); const command = new ConfirmSignUpCommand({ ClientId: clientId, Username: username, ConfirmationCode: code, }); return client.send(command); }; import qrcode from "qrcode-terminal"; import { log } from "@aws-doc-sdk-examples/lib/utils/util-log.js"; import { adminInitiateAuth } from "../../../actions/admin-initiate-auth.js"; import { associateSoftwareToken } from "../../../actions/associate-software-token.js"; import { FILE_USER_POOLS } from "./constants.js"; import { getFirstEntry } from "@aws-doc-sdk-examples/lib/utils/util-csv.js"; const handleMfaSetup = async (session, username) => { const { SecretCode, Session } = await associateSoftwareToken(session); // Store the Session for use with 'VerifySoftwareToken'. process.env.SESSION = Session; console.log( "Scan this code in your preferred authenticator app, then run 'verify-software-token' to finish the setup.", ); qrcode.generate( `otpauth://totp/${username}?secret=${SecretCode}`, { small: true }, console.log, ); }; const handleSoftwareTokenMfa = (session) => { // Store the Session for use with 'AdminRespondToAuthChallenge'. process.env.SESSION = session; }; const validateClient = (id) => { if (!id) { throw new Error( `User pool client id is missing. Did you run 'create-user-pool'?`, ); } }; const validateId = (id) => { if (!id) { throw new Error(`User pool id is missing. Did you run 'create-user-pool'?`); } }; const validateUser = (username, password) => { if (!(username && password)) { throw new Error( `Username and password must be provided as arguments to the 'admin-initiate-auth' command.`, ); } }; const adminInitiateAuthHandler = async (commands) => { const [_, username, password] = commands; try { validateUser(username, password); const [userPoolId, clientId] = getFirstEntry(FILE_USER_POOLS); validateId(userPoolId); validateClient(clientId); log("Signing in."); const { ChallengeName, Session } = await adminInitiateAuth({ clientId, userPoolId, username, password, }); if (ChallengeName === "MFA_SETUP") { log("MFA setup is required."); return handleMfaSetup(Session, username); } if (ChallengeName === "SOFTWARE_TOKEN_MFA") { handleSoftwareTokenMfa(Session); log(`Run 'admin-respond-to-auth-challenge ${username} <totp>'`); } } catch (err) { log(err); } }; export { adminInitiateAuthHandler }; const adminInitiateAuth = ({ clientId, userPoolId, username, password }) => { const client = new CognitoIdentityProviderClient({}); const command = new AdminInitiateAuthCommand({ ClientId: clientId, UserPoolId: userPoolId, AuthFlow: AuthFlowType.ADMIN_USER_PASSWORD_AUTH, AuthParameters: { USERNAME: username, PASSWORD: password }, }); return client.send(command); }; import { log } from "@aws-doc-sdk-examples/lib/utils/util-log.js"; import { adminRespondToAuthChallenge } from "../../../actions/admin-respond-to-auth-challenge.js"; import { getFirstEntry } from "@aws-doc-sdk-examples/lib/utils/util-csv.js"; import { FILE_USER_POOLS } from "./constants.js"; const verifyUsername = (username) => { if (!username) { throw new Error( `Username is missing. It must be provided as an argument to the 'admin-respond-to-auth-challenge' command.`, ); } }; const verifyTotp = (totp) => { if (!totp) { throw new Error( `Time-based one-time password (TOTP) is missing. It must be provided as an argument to the 'admin-respond-to-auth-challenge' command.`, ); } }; const storeAccessToken = (token) => { process.env.AccessToken = token; }; const adminRespondToAuthChallengeHandler = async (commands) => { const [_, username, totp] = commands; try { verifyUsername(username); verifyTotp(totp); const [userPoolId, clientId] = getFirstEntry(FILE_USER_POOLS); const session = process.env.SESSION; const { AuthenticationResult } = await adminRespondToAuthChallenge({ clientId, userPoolId, username, totp, session, }); storeAccessToken(AuthenticationResult.AccessToken); log("Successfully authenticated."); } catch (err) { log(err); } }; export { adminRespondToAuthChallengeHandler }; const respondToAuthChallenge = ({ clientId, username, session, userPoolId, code, }) => { const client = new CognitoIdentityProviderClient({}); const command = new RespondToAuthChallengeCommand({ ChallengeName: ChallengeNameType.SOFTWARE_TOKEN_MFA, ChallengeResponses: { SOFTWARE_TOKEN_MFA_CODE: code, USERNAME: username, }, ClientId: clientId, UserPoolId: userPoolId, Session: session, }); return client.send(command); }; import { log } from "@aws-doc-sdk-examples/lib/utils/util-log.js"; import { verifySoftwareToken } from "../../../actions/verify-software-token.js"; const validateTotp = (totp) => { if (!totp) { throw new Error( `Time-based one-time password (TOTP) must be provided to the 'validate-software-token' command.`, ); } }; const verifySoftwareTokenHandler = async (commands) => { const [_, totp] = commands; try { validateTotp(totp); log("Verifying TOTP."); await verifySoftwareToken(totp); log("TOTP Verified. Run 'admin-initiate-auth' again to sign-in."); } catch (err) { console.log(err); } }; export { verifySoftwareTokenHandler }; const verifySoftwareToken = (totp) => { const client = new CognitoIdentityProviderClient({}); // The 'Session' is provided in the response to 'AssociateSoftwareToken'. const session = process.env.SESSION; if (!session) { throw new Error( "Missing a valid Session. Did you run 'admin-initiate-auth'?", ); } const command = new VerifySoftwareTokenCommand({ Session: session, UserCode: totp, }); return client.send(command); };