### Example Request to Start User Import Job Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StartUserImportJob.md This example demonstrates how to initiate a user import job using the StartUserImportJob API. Replace placeholder values with your actual Job ID and User Pool ID. ```bash aws cognito-idp start-user-import-job --job-id import-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx --user-pool-id us-east-1_xxxxxxxxx ``` -------------------------------- ### Clone and Copy Example Project Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-test-application-flutter.html Commands to clone the AWS SDK examples repository and copy the React example client to the project folder. ```bash cd ~/some/other/path ``` ```bash git clone https://github.com/awsdocs/aws-doc-sdk-examples.git ``` ```bash cp -r ./aws-doc-sdk-examples/javascriptv3/example_code/cognito-identity-provider/scenarios/cognito-developer-guide-react-example/frontend-client ~/path/to/project/folder/ ``` -------------------------------- ### Example: Search users by phone number prefix Source: https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-manage-user-accounts.md This example shows how to find users whose phone numbers start with a specific prefix. ```APIDOC ## Example: Search users by phone number prefix ### Request Body ```json { "AttributesToGet": null, "Filter": "phone_number ^= \"+1312\"", "Limit": 10, "UserPoolId": "us-east-1_samplepool" } ``` ``` -------------------------------- ### Sign Up User with MFA in Kotlin Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_Scenario_SignUpUserWithMfa_section.md This Kotlin code example performs a full user sign-up and MFA setup flow with Amazon Cognito. It requires client ID and pool ID as arguments and prompts the user for necessary details like username, password, email, and confirmation codes. Ensure your development environment is set up and credentials are configured. ```kotlin /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html TIP: To set up the required user pool, run the AWS Cloud Development Kit (AWS CDK) script provided in this GitHub repo at resources/cdk/cognito_scenario_user_pool_with_mfa. This code example performs the following operations: 1. Invokes the signUp method to sign up a user. 2. Invokes the adminGetUser method to get the user's confirmation status. 3. Invokes the ResendConfirmationCode method if the user requested another code. 4. Invokes the confirmSignUp method. 5. Invokes the initiateAuth to sign in. This results in being prompted to set up TOTP (time-based one-time password). (The response is “ChallengeName”: “MFA_SETUP”). 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private key. This can be used with Google Authenticator. 7. Invokes the VerifySoftwareToken method to verify the TOTP and register for MFA. 8. Invokes the AdminInitiateAuth to sign in again. This results in being prompted to submit a TOTP (Response: “ChallengeName”: “SOFTWARE_TOKEN_MFA”). 9. Invokes the AdminRespondToAuthChallenge to get back a token. */ import java.util.Scanner import kotlin.system.exitProcess import software.amazon.awssdk.services.cognitoidentityprovider.model.* import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider suspend fun main(args: Array) { val usage = """ Usage: Where: clientId - The app client Id value that you can get from the AWS CDK script. poolId - The pool Id that you can get from the AWS CDK script. """ if (args.size != 2) { println(usage) exitProcess(1) } val clientId = args[0] val poolId = args[1] // Use the console to get data from the user. println("*** Enter your use name") val inOb = Scanner(System.`in`) val userName = inOb.nextLine() println(userName) println("*** Enter your password") val password: String = inOb.nextLine() println("*** Enter your email") val email = inOb.nextLine() println("*** Signing up $userName") signUp(clientId, userName, password, email) println("*** Getting $userName in the user pool") getAdminUser(userName, poolId) println("*** Conformation code sent to $userName. Would you like to send a new code? (Yes/No)") val ans = inOb.nextLine() if (ans.compareTo("Yes") == 0) { println("*** Sending a new confirmation code") resendConfirmationCode(clientId, userName) } println("*** Enter the confirmation code that was emailed") val code = inOb.nextLine() confirmSignUp(clientId, code, userName) println("*** Rechecking the status of $userName in the user pool") getAdminUser(userName, poolId) val authResponse = checkAuthMethod(clientId, userName, password, poolId) val mySession = authResponse.session val newSession = getSecretForAppMFA(mySession) println("*** Enter the 6-digit code displayed in Google Authenticator") val myCode = inOb.nextLine() // Verify the TOTP and register for MFA. verifyTOTP(newSession, myCode) println("*** Re-enter a 6-digit code displayed in Google Authenticator") val mfaCode: String = inOb.nextLine() val authResponse1 = checkAuthMethod(clientId, userName, password, poolId) val session2 = authResponse1.session adminRespondToAuthChallenge(userName, clientId, mfaCode, session2) } suspend fun checkAuthMethod( clientIdVal: String, userNameVal: String, passwordVal: String, userPoolIdVal: String, ): AdminInitiateAuthResponse { val authParas = mutableMapOf() authParas["USERNAME"] = userNameVal authParas["PASSWORD"] = passwordVal val authRequest = AdminInitiateAuthRequest { clientId = clientIdVal userPoolId = userPoolIdVal authParameters = authParas authFlow = AuthFlowType.AdminUserPasswordAuth } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminInitiateAuth(authRequest) println("Result Challenge is ${response.challengeName}") return response } } suspend fun resendConfirmationCode( clientIdVal: String?, userNameVal: String?, ) { val codeRequest = ResendConfirmationCodeRequest { clientId = clientIdVal username = userNameVal } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.resendConfirmationCode(codeRequest) ``` ```kotlin suspend fun signUp(clientIdVal: String, userNameVal: String, passwordVal: String, emailVal: String) { val signUpRequest = SignUpRequest { clientId = clientIdVal username = userNameVal password = passwordVal // Add the email attribute to the user attributes list. userAttributes = listOf( AttributeType { name = "email" value = emailVal } ) } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.signUp(signUpRequest) println("User ${response.userSub} was signed up.") } } ``` ```kotlin suspend fun getAdminUser(userNameVal: String, userPoolIdVal: String) { val adminUserRequest = AdminGetUserRequest { username = userNameVal userPoolId = userPoolIdVal } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminGetUser(adminUserRequest) println("User status: ${response.userStatus}") } } ``` ```kotlin suspend fun confirmSignUp(clientIdVal: String, codeVal: String, userNameVal: String) { val confirmSignUpRequest = ConfirmSignUpRequest { clientId = clientIdVal confirmationCode = codeVal username = userNameVal } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.confirmSignUp(confirmSignUpRequest) println("User $userNameVal was confirmed.") } } ``` ```kotlin suspend fun getSecretForAppMFA(sessionVal: String?): String? { val associateSoftwareTokenRequest = AssociateSoftwareTokenRequest { session = sessionVal } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.associateSoftwareToken(associateSoftwareTokenRequest) println("Secret code: ${response.secretCode}") return response.secretCode } } ``` ```kotlin suspend fun verifyTOTP(sessionVal: String?, codeVal: String?) { val verifySoftwareTokenRequest = VerifySoftwareTokenRequest { session = sessionVal softwareTokenMfaCode = codeVal username = "testuser" // Replace with actual username } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.verifySoftwareToken(verifySoftwareTokenRequest) println("TOTP verified successfully.") } } ``` ```kotlin suspend fun adminRespondToAuthChallenge(userNameVal: String, clientIdVal: String, mfaCodeVal: String, sessionVal: String?) { val challengeResponses = mutableMapOf() challengeResponses["USERNAME"] = userNameVal challengeResponses["SOFTWARE_TOKEN_MFA_CODE"] = mfaCodeVal val adminRespondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest { clientId = clientIdVal challengeName = ChallengeNameType.SOFTWARE_TOKEN_MFA challengeResponses = challengeResponses session = sessionVal } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminRespondToAuthChallenge(adminRespondToAuthChallengeRequest) println("Authentication successful. Access token: ${response.authenticationResult?.accessToken}") } } ``` -------------------------------- ### InitiateAuth API - SOFTWARE_TOKEN_MFA Example Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.md This example demonstrates initiating authentication with a software token MFA challenge. ```APIDOC ## POST / /api/v1/auth/initiate ### Description Initiates the authentication process for a user, potentially involving multi-factor authentication. ### Method POST ### Endpoint / /api/v1/auth/initiate ### Request Body - **AuthFlow** (string) - Required - The type of authentication flow to use. - **ClientId** (string) - Required - The client ID of the application. - **AuthParameters** (object) - Required - Parameters specific to the authentication flow. - **USERNAME** (string) - Required - The username of the user. - **PASSWORD** (string) - Required - The password of the user. - **SOFTWARE_TOKEN_MFA** (string) - Required - The software token MFA code. ### Request Example { "AuthFlow": "SOFTWARE_TOKEN_MFA", "ClientId": "1example23456789", "AuthParameters": { "USERNAME": "mytestuser", "SOFTWARE_TOKEN_MFA": "123456" } } ### Response #### Success Response (200) - **ChallengeName** (string) - The name of the challenge to be presented to the user. - **ChallengeParameters** (object) - Parameters for the challenge. - **USER_ID_FOR_SRP** (string) - User ID for SRP. - **FRIENDLY_DEVICE_NAME** (string) - Friendly name of the device. - **Session** (string) - The session token. #### Response Example { "ChallengeName": "SOFTWARE_TOKEN_MFA", "ChallengeParameters": { "USER_ID_FOR_SRP": "mytestuser", "FRIENDLY_DEVICE_NAME": "mytestauthenticator" }, "Session": "AYABeC1-y8qooiuysEv0uM4wAqQAHQABAAdTZXJ2aWNlABBDb2duaXRvVXNlclBvb2xzAAEAB2F3cy1rbXMAS2Fybjphd3M6a21zOnVzLXd..." } ``` -------------------------------- ### Example Request to Get Passkey Registration Options Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StartWebAuthnRegistration.md This example demonstrates how to request passkey registration options for the currently signed-in user using the StartWebAuthnRegistration API. Ensure the AccessToken includes the 'aws.cognito.signin.user.admin' scope. ```json { "AccessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" } ``` -------------------------------- ### Initiate Passkey Authentication Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.md Starts the user authentication flow using a passkey. This example is suitable when user verification is set to 'preferred' for the user pool. ```HTTP POST HTTP/1.1 Host: cognito-idp.us-east-1.amazonaws.com X-Amz-Date: 20230613T200059Z Accept-Encoding: gzip, deflate, br X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth User-Agent: Authorization: AWS4-HMAC-SHA256 Credential=, SignedHeaders=, Signature= Content-Length: { "AuthFlow": "USER_AUTH", "ClientId": "1example23456789", "AuthParameters": { "USERNAME": "testuser", "PREFERRED_CHALLENGE": "WEB_AUTHN" } } ``` ```HTTP HTTP/1.1 200 OK Date: Tue, 13 Jun 2023 20:00:59 GMT Content-Type: application/x-amz-json-1.0 Content-Length: x-amzn-requestid: a1b2c3d4-e5f6-a1b2-c3d4-EXAMPLE11111 Connection: keep-alive { "AvailableChallenges": [ "PASSWORD_SRP", "PASSWORD", "EMAIL_OTP", "WEB_AUTHN" ], "ChallengeName": "WEB_AUTHN", "ChallengeParameters": { "CREDENTIAL_REQUEST_OPTIONS": "{\"challenge\":\"[challenge string]\",\"timeout\":180000,\"rpId\":\"auth.example.com\",\"allowCredentials\":[{\"type\":\"public-key\",\"id\":\"[key ID]\",\"transports\":[]},{\"type\":\"public-key\",\"id\":\"[key ID]\",\"transports\":[\"internal\"]}],\"userVerification\":\"preferred\"}" }, "Session": "AYABeC1-y8qooiuysEv0uM4wAqQAHQABAAdTZXJ2aWNlABBDb2duaXRvVXNlclBvb2xzAAEAB2F3cy1rbXMAS2Fybjphd3M6a21zOnVzLXd..." } ``` -------------------------------- ### Install Dependencies Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-test-application-flutter.html Install the required project dependencies. ```bash npm install ``` -------------------------------- ### Example Request to List User Pool Replicas Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUserPoolReplicas.md This example demonstrates how to list all replicas for a specific user pool, identified by its ID. ```bash aws cognito-idp list-user-pool-replicas --user-pool-id us-east-1_EXAMPLE ``` -------------------------------- ### Clone Example React Project Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-user-pools-application-other-options.md Clone the example React project from the AWS code examples repository on GitHub. ```bash git clone https://github.com/awsdocs/aws-doc-sdk-examples.git ``` -------------------------------- ### Example Request for DescribeManagedLoginBranding Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeManagedLoginBranding.md This example demonstrates how to request the details for a specific managed login branding style using its ID. ```bash # The following example request returns the details of the managed login style with ID `a1b2c3d4-5678-90ab-cdef-EXAMPLE11111`. ``` -------------------------------- ### SetUICustomization API Example Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUICustomization.md This example demonstrates a successful response from the SetUICustomization API, showing the returned UI customization details. ```APIDOC ## SetUICustomization API ### Description Sets the UI customization settings for a user pool. This API allows you to provide custom CSS, images, and other visual elements to tailor the appearance of the Amazon Cognito hosted UI. ### Method POST ### Endpoint /api/users/SetUICustomization ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ClientId** (string) - Required - The client ID of the app associated with the user pool. - **UserPoolId** (string) - Required - The ID of the user pool. - **CSS** (string) - Optional - Custom CSS to be applied to the hosted UI. - **CSSUrl** (string) - Optional - A URL to a CSS file to be applied to the hosted UI. - **ImageUrl** (string) - Optional - A URL to an image to be used in the hosted UI. ### Request Example ```json { "ClientId": "1example23456789", "UserPoolId": "us-west-2_EXAMPLE", "CSS": ".logo-customizable {\n\tmax-width: 60%;\n\tmax-height: 30%;\n}", "ImageUrl": "https://auth.example.com/1example23456789/20250109170543/assets/images/image.jpg" } ``` ### Response #### Success Response (200) - **UICustomization** (object) - Contains the UI customization settings. - **ClientId** (string) - The client ID. - **CSS** (string) - The custom CSS. - **CSSUrl** (string) - The URL of the custom CSS file. - **CSSVersion** (string) - The version of the custom CSS. - **ImageUrl** (string) - The URL of the custom image. - **UserPoolId** (string) - The user pool ID. #### Response Example ```json { "UICustomization": { "ClientId": "1example23456789", "CSS": ".logo-customizable {\n\tmax-width: 60%;\n\tmax-height: 30%;\n}\n.banner-customizable {\n\tpadding: 25px 0px 25px 0px;\n\tbackground-color: lightgray;\n}\n.label-customizable {\n\tfont-weight: 400;\n}\n.textDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.idpDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.legalText-customizable {\n\tcolor: #747474;\n\tfont-size: 11px;\n}\n.submitButton-customizable {\n\tfont-size: 11px;\n\tfont-weight: normal;\n\tmargin: 20px -15px 10px -13px;\n\theight: 40px;\n\twidth: 108%;\n\tcolor: #fff;\n\tbackground-color: #337ab7;\n\ttext-align: center;\n}\n.submitButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #286090;\n}\n.errorMessage-customizable {\n\tpadding: 5px;\n\tfont-size: 14px;\n\twidth: 100%;\n\tbackground: #F5F5F5;\n\tborder: 2px solid #D64958;\n\tcolor: #D64958;\n}\n.inputField-customizable {\n\twidth: 100%;\n\theight: 34px;\n\tcolor: #555;\n\tbackground-color: #fff;\n\tborder: 1px solid #ccc;\n\tborder-radius: 0px;\n}\n.inputField-customizable:focus {\n\tborder-color: #66afe9;\n\toutline: 0;\n}\n.idpButton-customizable {\n\theight: 40px;\n\twidth: 100%;\n\twidth: 100%;\n\ttext-align: center;\n\tmargin-bottom: 15px;\n\tcolor: #fff;\n\tbackground-color: #5bc0de;\n\tborder-color: #46b8da;\n}\n.idpButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #31b0d5;\n}\n.socialButton-customizable {\n\tborder-radius: 2px;\n\theight: 40px;\n\tmargin-bottom: 15px;\n\tpadding: 1px;\n\ttext-align: left;\n\twidth: 100%;\n}\n.redirect-customizable {\n\ttext-align: center;\n}\n.passwordCheck-notValid-customizable {\n\tcolor: #DF3312;\n}\n.passwordCheck-valid-customizable {\n\tcolor: #19BF00;\n}\n.background-customizable {\n\tbackground-color: #fff;\n}\n", "CSSUrl": "https://auth.example.com/1example23456789/20250109170543/assets/CSS/custom-css.css", "CSSVersion": "20250109170543", "ImageUrl": "https://auth.example.com/1example23456789/20250109170543/assets/images/image.jpg", "UserPoolId": "us-west-2_EXAMPLE" } } ``` ``` -------------------------------- ### Example GET /oauth2/userInfo Request Source: https://docs.aws.amazon.com/cognito/latest/developerguide/userinfo-endpoint.md This example shows a sample GET request to the /oauth2/userInfo endpoint. Ensure the Authorization header contains a valid Bearer access token. ```HTTP GET /oauth2/userInfo HTTP/1.1 Content-Type: application/x-amz-json-1.1 Authorization: Bearer eyJra12345EXAMPLE User-Agent: {{[User agent]}} Accept: */* Host: auth.example.com Accept-Encoding: gzip, deflate, br Connection: keep-alive ``` -------------------------------- ### Start the Frontend Server Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-identity-pools-application.md Navigate to the frontend directory and start the HTTP server. This will serve the demo application's user interface to your browser. ```bash cd frontend python -m http.server 8001 ``` -------------------------------- ### Start the Backend Server Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-identity-pools-application.md Navigate to the backend directory and run the OAuth server script. This server handles authentication flows for the demo. ```bash cd backend python oauth_server.py ``` -------------------------------- ### Launch Development Server Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-test-application-flutter.html Start the application in development mode. ```bash npm run dev ``` -------------------------------- ### Cognito User Import Job - Pending Status Response Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.md This is an example of a successful response when starting a user import job, indicating the job is pending. ```json { "UserImportJob": { "Status": "Pending", "StartDate": 1470957851.483, "UserPoolId": "{{USER_POOL_ID}}", "ImportedUsers": 0, "SkippedUsers": 0, "JobName": "{{JOB_NAME}}", "JobId": "{{JOB_ID}}", "PreSignedUrl":"{{PRE_SIGNED_URL}}", "CloudWatchLogsRoleArn": "{{ROLE_ARN}}", "FailedUsers": 0, "CreationDate": 1470957431.965 } } ``` -------------------------------- ### Get MFA and WebAuthn Configuration for User Pool Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserPoolMfaConfig.md This example demonstrates how to retrieve the MFA and WebAuthn configuration for a given user pool using a POST request. ```http POST HTTP/1.1 Host: cognito-idp.us-west-2.amazonaws.com X-Amz-Date: 20230613T200059Z Accept-Encoding: gzip, deflate, br X-Amz-Target: AWSCognitoIdentityProviderService.GetUserPoolMfaConfig User-Agent: Authorization: AWS4-HMAC-SHA256 Credential=, SignedHeaders=, Signature= Content-Length: { "UserPoolId": "us-west-2_EXAMPLE" } ``` -------------------------------- ### List User Pools using AWS SDK for Go V2 Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_ListUserPools_section.md This Go V2 code example demonstrates how to list user pools in your AWS account. It utilizes the `ListUserPools` operation and paginator for handling multiple pages of results. For complete setup and running instructions, refer to the AWS Code Examples Repository. ```APIDOC ## ListUserPools (Go V2) ### Description Lists user pools in your AWS account using the AWS SDK for Go V2. ### Method `cognitoidentityprovider.NewListUserPoolsPaginator` and `paginator.NextPage` ### Parameters - `MaxResults` (int32) - Optional - The maximum number of results to return. ### Request Example ```go package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" ) func main() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } cognitoClient := cognitoidentityprovider.NewFromConfig(sdkConfig) fmt.Println("Let's list the user pools for your account.") var pools []types.UserPoolDescriptionType paginator := cognitoidentityprovider.NewListUserPoolsPaginator( cognitoClient, &cognitoidentityprovider.ListUserPoolsInput{MaxResults: aws.Int32(10)} // Example: MaxResults set to 10 ) for paginator.HasMorePages() { output, err := paginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get user pools. Here's why: %v\n", err) } else { pools = append(pools, output.UserPools...) } } if len(pools) == 0 { fmt.Println("You don't have any user pools!") } else { for _, pool := range pools { fmt.Printf("\t%v: %v\n", *pool.Name, *pool.Id) } } } ``` ### Response #### Success Response (200) - `UserPools` ([]types.UserPoolDescriptionType) - A list of user pool descriptions. - `NextToken` (string) - An optional pagination token. #### Response Example ```json { "UserPools": [ { "Id": "us-east-1_xxxxxxxxx", "Name": "MyUserPool", "Status": "Active", "LastModifiedDate": "2023-01-01T12:00:00Z", "CreationDate": "2022-01-01T12:00:00Z", "Arn": "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_xxxxxxxxx", "Policies": {}, "SmsConfiguration": {}, "EmailConfiguration": {}, "VerificationMessageTemplate": {}, "SmsSecurityQuestionDefaults": {}, "UserAttributeUpdateSettings": {}, "DeviceConfiguration": {}, "EdgeSecurityPolicy": "M TLS 1.2", "SmsRulesConfigurations": [], "Domain": "myuserpool.auth.us-east-1.amazoncognito.com" } ], "NextToken": "" } ``` ``` -------------------------------- ### Launch React Application Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-user-pools-application-other-options.md Start the development server for your React application. ```bash npm run dev ``` -------------------------------- ### Navigate to the Demo Application Directory Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-identity-pools-application.md Change your current directory to the web application folder within the cloned repository. This is where you'll configure and run the demo. ```bash cd python/example_code/cognito/scenarios/identity_pools_example_demo/web ``` -------------------------------- ### InitiateAuth - Passkey Authentication Flow Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.md Starts the user authentication flow using a passkey. This example assumes the user pool supports password, passkey, and OTP, with user verification set to 'preferred'. ```APIDOC ## POST / ### Description Initiates an authentication flow for a user, specifically demonstrating the passkey authentication flow. ### Method POST ### Endpoint / ### Parameters #### Headers - **Host**: cognito-idp.us-east-1.amazonaws.com - **X-Amz-Date**: 20230613T200059Z - **Accept-Encoding**: gzip, deflate, br - **X-Amz-Target**: AWSCognitoIdentityProviderService.InitiateAuth - **User-Agent**: - **Authorization**: AWS4-HMAC-SHA256 Credential=, SignedHeaders=, Signature= - **Content-Length**: #### Request Body - **AuthFlow** (string) - Required - The authentication flow to use (e.g., "USER_AUTH"). - **ClientId** (string) - Required - The ID of the client. - **AuthParameters** (object) - Required - A map of sensitive attribute names to values for the authentication request. - **USERNAME** (string) - Required - The user's username. - **PREFERRED_CHALLENGE** (string) - Required - The preferred authentication challenge (e.g., "WEB_AUTHN"). ### Request Example ```json { "AuthFlow": "USER_AUTH", "ClientId": "1example23456789", "AuthParameters": { "USERNAME": "testuser", "PREFERRED_CHALLENGE": "WEB_AUTHN" } } ``` ### Response #### Success Response (200) - **AvailableChallenges** (array) - A list of challenges that are available for the user. - **ChallengeName** (string) - The name of the challenge that Amazon Cognito is returning. - **ChallengeParameters** (object) - The parameters that Amazon Cognito is returning. These parameters are required to continue the authentication process. - **CREDENTIAL_REQUEST_OPTIONS** (string) - Options for credential requests, including challenge details, timeout, and allowed credentials. - **Session** (string) - The session token for the authentication. #### Response Example ```json { "AvailableChallenges": [ "PASSWORD_SRP", "PASSWORD", "EMAIL_OTP", "WEB_AUTHN" ], "ChallengeName": "WEB_AUTHN", "ChallengeParameters": { "CREDENTIAL_REQUEST_OPTIONS": "{\"challenge\":\"[challenge string]\",\"timeout\":180000,\"rpId\":\"auth.example.com\",\"allowCredentials\":[{\"type\":\"public-key\",\"id\":\"[key ID]\",\"transports\":[]},{\"type\":\"public-key\",\"id\":\"[key ID]\",\"transports\":[\"internal\"]}],\"userVerification\":\"preferred\"}" }, "Session": "AYABeC1-y8qooiuysEv0uM4wAqQAHQABAAdTZXJ2aWNlABBDb2duaXRvVXNlclBvb2xzAAEAB2F3cy1rbXMAS2Fybjphd3M6a21zOnVzLXd..." } ``` ``` -------------------------------- ### Sign In and Set Up MFA Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_Scenario_SignUpUserWithMfa_section.md Initiates the sign-in process, handles the MFA setup challenge by generating a QR code for an authenticator app, and verifies the MFA code. It then proceeds to respond to the software token MFA challenge to complete sign-in. ```Python print("Let's sign in and get an access token.") auth_tokens = None challenge = "ADMIN_USER_PASSWORD_AUTH" response = {} while challenge is not None: if challenge == "ADMIN_USER_PASSWORD_AUTH": response = cog_wrapper.start_sign_in(user_name, password) challenge = response["ChallengeName"] elif response["ChallengeName"] == "MFA_SETUP": print("First, we need to set up an MFA application.") qr_img = qrcode.make( f"otpauth://totp/{user_name}?secret={response['SecretCode']}" ) qr_img.save("qr.png") q.ask( "Press Enter to see a QR code on your screen. Scan it into an MFA " "application, such as Google Authenticator." ) webbrowser.open("qr.png") mfa_code = q.ask( "Enter the verification code from your MFA application: ", q.non_empty ) response = cog_wrapper.verify_mfa(response["Session"], mfa_code) print(f"MFA device setup {response['Status']}") print("Now that an MFA application is set up, let's sign in again.") print( "You might have to wait a few seconds for a new MFA code to appear in " "your MFA application." ) challenge = "ADMIN_USER_PASSWORD_AUTH" elif response["ChallengeName"] == "SOFTWARE_TOKEN_MFA": auth_tokens = None while auth_tokens is None: mfa_code = q.ask( "Enter a verification code from your MFA application: ", q.non_empty ) auth_tokens = cog_wrapper.respond_to_mfa_challenge( user_name, response["Session"], mfa_code ) print(f"You're signed in as {user_name}.") print("Here's your access token:") pp(auth_tokens["AccessToken"]) print("And your device information:") pp(auth_tokens["NewDeviceMetadata"]) challenge = None else: raise Exception(f"Got unexpected challenge {response['ChallengeName']}") print("-" * 88) ``` -------------------------------- ### Get MFA Secret for Software Token in Python Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_Scenario_SignUpUserWithMfa_section.md Retrieves an MFA secret token required to associate a software token (like a time-based one-time password app) with a user. This is part of the MFA setup flow. ```python def get_mfa_secret(self, session): """ Gets a token that can be used to associate an MFA application with the user. :param session: Session information returned from a previous call to initiate authentication. :return: An MFA token that can be used to set up an MFA application. """ try: response = self.cognito_idp_client.associate_software_token(Session=session) except ClientError as err: logger.error( "Couldn't get MFA secret. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: response.pop("ResponseMetadata", None) return response ``` -------------------------------- ### Start User Sign-in with Admin Credentials in Python Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_Scenario_SignUpUserWithMfa_section.md Initiates the sign-in process for a user using administrator credentials. This method is suitable for server-side applications. It handles MFA setup challenges if required by the user pool configuration. ```python def start_sign_in(self, user_name, password): """ Starts the sign-in process for a user by using administrator credentials. This method of signing in is appropriate for code running on a secure server. If the user pool is configured to require MFA and this is the first sign-in for the user, Amazon Cognito returns a challenge response to set up an MFA application. When this occurs, this function gets an MFA secret from Amazon Cognito and returns it to the caller. :param user_name: The name of the user to sign in. :param password: The user's password. :return: The result of the sign-in attempt. When sign-in is successful, this returns an access token that can be used to get AWS credentials. Otherwise, Amazon Cognito returns a challenge to set up an MFA application, or a challenge to enter an MFA code from a registered MFA application. """ try: kwargs = { "UserPoolId": self.user_pool_id, "ClientId": self.client_id, "AuthFlow": "ADMIN_USER_PASSWORD_AUTH", "AuthParameters": {"USERNAME": user_name, "PASSWORD": password}, } if self.client_secret is not None: kwargs["AuthParameters"]["SECRET_HASH"] = self._secret_hash(user_name) response = self.cognito_idp_client.admin_initiate_auth(**kwargs) challenge_name = response.get("ChallengeName", None) if challenge_name == "MFA_SETUP": if ( "SOFTWARE_TOKEN_MFA" in response["ChallengeParameters"]["MFAS_CAN_SETUP"] ): response.update(self.get_mfa_secret(response["Session"])) else: raise RuntimeError( "The user pool requires MFA setup, but the user pool is not " "configured for TOTP MFA. This example requires TOTP MFA." ) except ClientError as err: logger.error( "Couldn't start sign in for %s. Here's why: %s: %s", user_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: response.pop("ResponseMetadata", None) return response ``` -------------------------------- ### MFA_SETUP Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ChallengeResponseType.md Response structure for the MFA_SETUP challenge, used to set up MFA. ```APIDOC ## MFA_SETUP ### Description Response structure for the MFA_SETUP challenge, used to set up MFA. ### Method Not Applicable (This is a response structure, not an API endpoint) ### Endpoint Not Applicable ### Parameters #### ChallengeResponses - **USERNAME** (string) - Required - The username of the user. ### Request Example ```json { "ChallengeName": "MFA_SETUP", "ChallengeResponses": { "USERNAME": "[username]" }, "SESSION": "[Session ID from VerifySoftwareToken]" } ``` ### Response #### Success Response This structure is part of a request, not a response. #### Response Example ```json { "ChallengeName": "MFA_SETUP", "ChallengeResponses": { "USERNAME": "[username]" }, "SESSION": "[Session ID from VerifySoftwareToken]" } ``` ``` -------------------------------- ### Get Secret for App MFA Setup in Swift Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_Scenario_SignUpUserWithMfa_section.md This function retrieves the secret code required to set up app-based MFA for a user. It uses the AssociateSoftwareToken API and requires an active authentication session. Handles SoftwareTokenMFANotFoundException if MFA is not configured. ```swift func getSecretForAppMFA(cipClient: CognitoIdentityProviderClient, authSession: String?) async -> String? { do { let output = try await cipClient.associateSoftwareToken( input: AssociateSoftwareTokenInput( session: authSession ) ) guard let secretCode = output.secretCode else { print("*** Unable to get the secret code") return nil } print("=====> Enter this token into Google Authenticator: \(secretCode)") return output.session } catch _ as SoftwareTokenMFANotFoundException { print("*** The specified user pool isn't configured for MFA.") return nil } catch { print("*** An unexpected error occurred getting the secret for the app's MFA.") return nil } } ``` -------------------------------- ### Install Backend Dependencies Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-identity-pools-application.md Install the necessary Python packages for the backend of the demo application using pip. Ensure you have a virtual environment activated if preferred. ```bash pip install -r requirements.txt ``` -------------------------------- ### Cognito Identity Provider Swift Example Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_Scenario_SignUpUserWithMfa_section.md A Swift command-line application demonstrating various Amazon Cognito Identity Provider features. It requires setting up credentials and a user pool, and performs user sign-up, confirmation, and MFA setup. ```swift // An example demonstrating various features of Amazon Cognito. Before running // this Swift code example, set up your development environment, including // your credentials. // // For more information, see the following documentation: // https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html // // TIP: To set up the required user pool, run the AWS Cloud Development Kit // (AWS CDK) script provided in this GitHub repo at // resources/cdk/cognito_scenario_user_pool_with_mfa. // // This example performs the following functions: // // 1. Invokes the signUp method to sign up a user. // 2. Invokes the adminGetUser method to get the user's confirmation status. // 3. Invokes the ResendConfirmationCode method if the user requested another // code. // 4. Invokes the confirmSignUp method. // 5. Invokes the initiateAuth to sign in. This results in being prompted to // set up TOTP (time-based one-time password). (The response is // “ChallengeName”: “MFA_SETUP”). // 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private // key. This can be used with Google Authenticator. // 7. Invokes the VerifySoftwareToken method to verify the TOTP and register // for MFA. // 8. Invokes the AdminInitiateAuth to sign in again. This results in being // prompted to submit a TOTP (Response: “ChallengeName”: // “SOFTWARE_TOKEN_MFA”). // 9. Invokes the AdminRespondToAuthChallenge to get back a token. import ArgumentParser import Foundation import AWSClientRuntime import AWSCognitoIdentityProvider struct ExampleCommand: ParsableCommand { @Argument(help: "The application clientId.") var clientId: String @Argument(help: "The user pool ID to use.") var poolId: String @Option(help: "Name of the Amazon Region to use") var region = "us-east-1" static var configuration = CommandConfiguration( commandName: "cognito-scenario", abstract: """ Demonstrates various features of Amazon Cognito. """, discussion: """ """ ) /// Prompt for an input string of at least a minimum length. /// /// - Parameters: /// - prompt: The prompt string to display. /// - minLength: The minimum number of characters to allow in the /// response. Default value is 0. /// /// - Returns: The entered string. func stringRequest(_ prompt: String, minLength: Int = 1) -> String { while true { print(prompt, terminator: "") let str = readLine() guard let str else { continue } if str.count >= minLength { return str } else { print("*** Response must be at least \(minLength) character(s) long.") } } } /// Ask a yes/no question. /// /// - Parameter prompt: A prompt string to print. /// /// - Returns: `true` if the user answered "Y", otherwise `false`. func yesNoRequest(_ prompt: String) -> Bool { while true { let answer = stringRequest(prompt).lowercased() if answer == "y" || answer == "n" { return answer == "y" } } } /// Get information about a specific user in a user pool. /// /// - Parameters: /// - cipClient: The Amazon Cognito Identity Provider client to use. ``` -------------------------------- ### InitiateAuth Setup in Go Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_InitiateAuth_section.md Initializes the Cognito client structure for use with the AWS SDK for Go V2. ```go import ( "context" "errors" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" ) type CognitoActions struct { CognitoClient *cognitoidentityprovider.Client } ``` -------------------------------- ### MFA_SETUP Challenge Response Source: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ChallengeResponseType.md Respond to the MFA_SETUP challenge by providing the USERNAME and the SESSION ID from VerifySoftwareToken. ```json "ChallengeName": "MFA_SETUP", "ChallengeResponses": {"USERNAME": "[username]"}, "SESSION": "[Session ID from VerifySoftwareToken]"} ``` -------------------------------- ### Sign Up User Async Source: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity-provider_example_cognito-identity-provider_Scenario_SignUpUserWithMfa_section.md Signs up a new user with the provided client ID, username, password, and email. Returns true if the HTTP status code is OK. ```.NET /// /// Sign up a new user. /// /// The client Id of the application. /// The username to use. /// The user's password. /// The email address of the user. /// A Boolean value indicating whether the user was confirmed. public async Task SignUpAsync(string clientId, string userName, string password, string email) { var userAttrs = new AttributeType { Name = "email", Value = email, }; var userAttrsList = new List(); userAttrsList.Add(userAttrs); var signUpRequest = new SignUpRequest { UserAttributes = userAttrsList, Username = userName, ClientId = clientId, Password = password }; var response = await _cognitoService.SignUpAsync(signUpRequest); return response.HttpStatusCode == HttpStatusCode.OK; } ``` -------------------------------- ### Initialize React Project Source: https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-test-application-flutter.html Create a new React service using Vite with the React TypeScript template. ```bash npm create vite@latest frontend-client -- --template react-ts ```