SDK for JavaScript (v3) を使用した Amazon Cognito ID プロバイダーの例 - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

SDK for JavaScript (v3) を使用した Amazon Cognito ID プロバイダーの例

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

開始方法

次のコード例は、Amazon Cognito の使用を開始する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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; };
  • API の詳細については、「 API リファレンスListUserPools」の「」を参照してください。 AWS SDK for JavaScript

アクション

次のコード例は、Amazon Cognito ユーザーを確認する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

const confirmSignUp = ({ clientId, username, code }) => { const client = new CognitoIdentityProviderClient({}); const command = new ConfirmSignUpCommand({ ClientId: clientId, Username: username, ConfirmationCode: code, }); return client.send(command); };
  • API の詳細については、「 API リファレンスConfirmSignUp」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito により追跡する MFA デバイスを確認する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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); };
  • API の詳細については、「 API リファレンスConfirmDevice」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、MFA アプリケーションを Amazon Cognito ユーザーに関連付けるトークンを取得する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

const associateSoftwareToken = (session) => { const client = new CognitoIdentityProviderClient({}); const command = new AssociateSoftwareTokenCommand({ Session: session, }); return client.send(command); };
  • API の詳細については、「 API リファレンスAssociateSoftwareToken」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito ユーザーに関する情報を取得する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

const adminGetUser = ({ userPoolId, username }) => { const client = new CognitoIdentityProviderClient({}); const command = new AdminGetUserCommand({ UserPoolId: userPoolId, Username: username, }); return client.send(command); };
  • API の詳細については、「 API リファレンスAdminGetUser」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito ユーザーを一覧表示する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

const listUsers = ({ userPoolId }) => { const client = new CognitoIdentityProviderClient({}); const command = new ListUsersCommand({ UserPoolId: userPoolId, }); return client.send(command); };
  • API の詳細については、「 API リファレンスListUsers」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito 確認コードを再送信する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

const resendConfirmationCode = ({ clientId, username }) => { const client = new CognitoIdentityProviderClient({}); const command = new ResendConfirmationCodeCommand({ ClientId: clientId, Username: username, }); return client.send(command); };
  • API の詳細については、「 API リファレンスResendConfirmationCode」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito SRP 認証チャレンジに応答する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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); };
  • API の詳細については、「 API リファレンスRespondToAuthChallenge」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito 認証チャレンジに応答する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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); };
  • API の詳細については、「 API リファレンスAdminRespondToAuthChallenge」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、ユーザーを Amazon Cognito にサインアップする方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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); };
  • API の詳細については、「 API リファレンスSignUp」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito を使用して認証を開始する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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); };
  • API の詳細については、「 API リファレンスInitiateAuth」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito と管理者認証情報を使用して認証を開始する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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); };
  • API の詳細については、「 API リファレンスAdminInitiateAuth」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon Cognito ユーザーで MFA アプリケーションを検証する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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); };
  • API の詳細については、「 API リファレンスVerifySoftwareToken」の「」を参照してください。 AWS SDK for JavaScript

シナリオ

次のコードサンプルは、以下の操作方法を示しています。

  • ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。

  • MFA アプリケーションをユーザーに関連付けて、多要素認証を設定します。

  • パスワードと MFA コードを使用してサインインします。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

最高のエクスペリエンスを得るには、 GitHub リポジトリのクローンを作成し、この例を実行します。次のコードは、サンプルアプリケーション全体のサンプルを表しています。

import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { signUp } from "../../../actions/sign-up.js"; import { FILE_USER_POOLS } from "./constants.js"; import { getSecondValuesFromEntries } from "@aws-sdk-examples/libs/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-sdk-examples/libs/utils/util-log.js"; import { confirmSignUp } from "../../../actions/confirm-sign-up.js"; import { FILE_USER_POOLS } from "./constants.js"; import { getSecondValuesFromEntries } from "@aws-sdk-examples/libs/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-sdk-examples/libs/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-sdk-examples/libs/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-sdk-examples/libs/utils/util-log.js"; import { adminRespondToAuthChallenge } from "../../../actions/admin-respond-to-auth-challenge.js"; import { getFirstEntry } from "@aws-sdk-examples/libs/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-sdk-examples/libs/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); };