使用适用于 JavaScript (v3) 的软件开发工具包的 Amazon Cognito 身份提供商示例 - AWS SDK 代码示例

文档 AWS SDK 示例 GitHub 存储库中还有更多 S AWS DK 示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用适用于 JavaScript (v3) 的软件开发工具包的 Amazon Cognito 身份提供商示例

以下代码示例演示如何将 AWS SDK for JavaScript (v3) 与 Amazon Cognito Identity Provider 结合使用来执行操作和实现常见场景。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是指显示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

开始使用

以下代码示例演示了如何开始使用 Amazon Cognito。

适用于 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 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考ListUserPools中的。

操作

以下代码示例演示了如何确认 Amazon Cognito 用户。

适用于 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 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考ConfirmSignUp中的。

以下代码示例演示了如何确认 MFA 设备可通过 Amazon Cognito 进行跟踪。

适用于 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 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考ConfirmDevice中的。

以下代码示例演示了如何获取令牌,以将 MFA 应用程序与 Amazon Cognito 用户关联。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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

以下代码示例演示了如何获取有关 Amazon Cognito 用户的信息。

适用于 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 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考AdminGetUser中的。

以下代码示例演示了如何列出 Amazon Cognito 用户。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

const listUsers = ({ userPoolId }) => { const client = new CognitoIdentityProviderClient({}); const command = new ListUsersCommand({ UserPoolId: userPoolId, }); return client.send(command); };
  • 有关 API 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考ListUsers中的。

以下代码示例演示了如何重新发送 Amazon Cognito 确认码。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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

以下代码示例演示了如何响应 Amazon Cognito SRP 身份验证质询。

适用于 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); };

以下代码示例演示了如何响应 Amazon Cognito 身份验证质询。

适用于 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); };

以下代码示例演示了如何向 Amazon Cognito 注册用户。

适用于 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 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考SignUp中的。

以下代码示例演示了如何通过 Amazon Cognito 开始身份验证。

适用于 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 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考InitiateAuth中的。

以下代码示例演示了如何使用 Amazon Cognito 和管理员凭证开始身份验证。

适用于 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 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考AdminInitiateAuth中的。

以下代码示例演示了如何向 Amazon Cognito 用户验证 MFA 应用程序。

适用于 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 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考VerifySoftwareToken中的。

场景

以下代码示例演示了操作流程:

  • 使用用户名、密码和电子邮件地址注册和确认用户。

  • 通过将 MFA 应用程序与用户关联来设置多重身份验证。

  • 使用密码和 MFA 代码登录。

适用于 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); };