Esempi di Amazon Cognito Identity Provider che utilizzano SDK per Kotlin - AWS Esempi di codice SDK

Sono disponibili altri esempi AWS SDK nel repository AWS Doc SDK Examples. GitHub

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempi di Amazon Cognito Identity Provider che utilizzano SDK per Kotlin

I seguenti esempi di codice mostrano come eseguire azioni e implementare scenari comuni utilizzando l' AWS SDK per Kotlin con Amazon Cognito Identity Provider.

Le operazioni sono estratti di codice da programmi più grandi e devono essere eseguite nel contesto. Sebbene le operazioni mostrino come richiamare le singole funzioni del servizio, è possibile visualizzarle contestualizzate negli scenari correlati.

Gli scenari sono esempi di codice che mostrano come eseguire un'attività specifica richiamando più funzioni all'interno dello stesso servizio o combinate con altri Servizi AWS.

Ogni esempio include un collegamento al codice sorgente completo, dove puoi trovare istruzioni su come configurare ed eseguire il codice nel contesto.

Operazioni

Il seguente esempio di codice mostra come utilizzareAdminGetUser.

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

suspend fun getAdminUser( userNameVal: String?, poolIdVal: String?, ) { val userRequest = AdminGetUserRequest { username = userNameVal userPoolId = poolIdVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminGetUser(userRequest) println("User status ${response.userStatus}") } }
  • Per i dettagli sull'API, AdminGetUserconsulta AWS SDK for Kotlin API reference.

Il seguente esempio di codice mostra come utilizzare. AdminInitiateAuth

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

suspend fun checkAuthMethod( clientIdVal: String, userNameVal: String, passwordVal: String, userPoolIdVal: String, ): AdminInitiateAuthResponse { val authParas = mutableMapOf<String, String>() authParas["USERNAME"] = userNameVal authParas["PASSWORD"] = passwordVal val authRequest = AdminInitiateAuthRequest { clientId = clientIdVal userPoolId = userPoolIdVal authParameters = authParas authFlow = AuthFlowType.AdminUserPasswordAuth } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminInitiateAuth(authRequest) println("Result Challenge is ${response.challengeName}") return response } }
  • Per i dettagli sull'API, AdminInitiateAuthconsulta AWS SDK for Kotlin API reference.

Il seguente esempio di codice mostra come utilizzare. AdminRespondToAuthChallenge

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

// Respond to an authentication challenge. suspend fun adminRespondToAuthChallenge( userName: String, clientIdVal: String?, mfaCode: String, sessionVal: String?, ) { println("SOFTWARE_TOKEN_MFA challenge is generated") val challengeResponsesOb = mutableMapOf<String, String>() challengeResponsesOb["USERNAME"] = userName challengeResponsesOb["SOFTWARE_TOKEN_MFA_CODE"] = mfaCode val adminRespondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest { challengeName = ChallengeNameType.SoftwareTokenMfa clientId = clientIdVal challengeResponses = challengeResponsesOb session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(adminRespondToAuthChallengeRequest) println("respondToAuthChallengeResult.getAuthenticationResult() ${respondToAuthChallengeResult.authenticationResult}") } }

Il seguente esempio di codice mostra come utilizzare. AssociateSoftwareToken

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

suspend fun getSecretForAppMFA(sessionVal: String?): String? { val softwareTokenRequest = AssociateSoftwareTokenRequest { session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest) val secretCode = tokenResponse.secretCode println("Enter this token into Google Authenticator") println(secretCode) return tokenResponse.session } }

Il seguente esempio di codice mostra come utilizzare. ConfirmSignUp

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

suspend fun confirmSignUp( clientIdVal: String?, codeVal: String?, userNameVal: String?, ) { val signUpRequest = ConfirmSignUpRequest { clientId = clientIdVal confirmationCode = codeVal username = userNameVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.confirmSignUp(signUpRequest) println("$userNameVal was confirmed") } }
  • Per i dettagli sull'API, ConfirmSignUpconsulta AWS SDK for Kotlin API reference.

Il seguente esempio di codice mostra come utilizzare. ListUsers

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

suspend fun listAllUsers(userPoolId: String) { val request = ListUsersRequest { this.userPoolId = userPoolId } CognitoIdentityProviderClient { region = "us-east-1" }.use { cognitoClient -> val response = cognitoClient.listUsers(request) response.users?.forEach { user -> println("The user name is ${user.username}") } } }
  • Per i dettagli sull'API, ListUsersconsulta AWS SDK for Kotlin API reference.

Il seguente esempio di codice mostra come utilizzare. ResendConfirmationCode

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

suspend fun resendConfirmationCode( clientIdVal: String?, userNameVal: String?, ) { val codeRequest = ResendConfirmationCodeRequest { clientId = clientIdVal username = userNameVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.resendConfirmationCode(codeRequest) println("Method of delivery is " + (response.codeDeliveryDetails?.deliveryMedium)) } }

Il seguente esempio di codice mostra come utilizzare. SignUp

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

suspend fun signUp( clientIdVal: String?, userNameVal: String?, passwordVal: String?, emailVal: String?, ) { val userAttrs = AttributeType { name = "email" value = emailVal } val userAttrsList = mutableListOf<AttributeType>() userAttrsList.add(userAttrs) val signUpRequest = SignUpRequest { userAttributes = userAttrsList username = userNameVal clientId = clientIdVal password = passwordVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.signUp(signUpRequest) println("User has been signed up") } }
  • Per i dettagli sull'API, SignUpconsulta AWS SDK for Kotlin API reference.

Il seguente esempio di codice mostra come utilizzare. VerifySoftwareToken

SDK per Kotlin
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

// Verify the TOTP and register for MFA. suspend fun verifyTOTP( sessionVal: String?, codeVal: String?, ) { val tokenRequest = VerifySoftwareTokenRequest { userCode = codeVal session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest) println("The status of the token is ${verifyResponse.status}") } }

Scenari

L'esempio di codice seguente mostra come:

  • Registra e conferma un utente con nome utente, password e indirizzo e-mail.

  • Configura l'autenticazione a più fattori associando un'applicazione MFA all'utente.

  • Accedi utilizzando una password e un codice MFA.

SDK per Kotlin
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/** 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. */ suspend fun main(args: Array<String>) { val usage = """ Usage: <clientId> <poolId> 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<String, String>() authParas["USERNAME"] = userNameVal authParas["PASSWORD"] = passwordVal val authRequest = AdminInitiateAuthRequest { clientId = clientIdVal userPoolId = userPoolIdVal authParameters = authParas authFlow = AuthFlowType.AdminUserPasswordAuth } CognitoIdentityProviderClient { 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 { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.resendConfirmationCode(codeRequest) println("Method of delivery is " + (response.codeDeliveryDetails?.deliveryMedium)) } } // Respond to an authentication challenge. suspend fun adminRespondToAuthChallenge( userName: String, clientIdVal: String?, mfaCode: String, sessionVal: String?, ) { println("SOFTWARE_TOKEN_MFA challenge is generated") val challengeResponsesOb = mutableMapOf<String, String>() challengeResponsesOb["USERNAME"] = userName challengeResponsesOb["SOFTWARE_TOKEN_MFA_CODE"] = mfaCode val adminRespondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest { challengeName = ChallengeNameType.SoftwareTokenMfa clientId = clientIdVal challengeResponses = challengeResponsesOb session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(adminRespondToAuthChallengeRequest) println("respondToAuthChallengeResult.getAuthenticationResult() ${respondToAuthChallengeResult.authenticationResult}") } } // Verify the TOTP and register for MFA. suspend fun verifyTOTP( sessionVal: String?, codeVal: String?, ) { val tokenRequest = VerifySoftwareTokenRequest { userCode = codeVal session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest) println("The status of the token is ${verifyResponse.status}") } } suspend fun getSecretForAppMFA(sessionVal: String?): String? { val softwareTokenRequest = AssociateSoftwareTokenRequest { session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest) val secretCode = tokenResponse.secretCode println("Enter this token into Google Authenticator") println(secretCode) return tokenResponse.session } } suspend fun confirmSignUp( clientIdVal: String?, codeVal: String?, userNameVal: String?, ) { val signUpRequest = ConfirmSignUpRequest { clientId = clientIdVal confirmationCode = codeVal username = userNameVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.confirmSignUp(signUpRequest) println("$userNameVal was confirmed") } } suspend fun getAdminUser( userNameVal: String?, poolIdVal: String?, ) { val userRequest = AdminGetUserRequest { username = userNameVal userPoolId = poolIdVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminGetUser(userRequest) println("User status ${response.userStatus}") } } suspend fun signUp( clientIdVal: String?, userNameVal: String?, passwordVal: String?, emailVal: String?, ) { val userAttrs = AttributeType { name = "email" value = emailVal } val userAttrsList = mutableListOf<AttributeType>() userAttrsList.add(userAttrs) val signUpRequest = SignUpRequest { userAttributes = userAttrsList username = userNameVal clientId = clientIdVal password = passwordVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.signUp(signUpRequest) println("User has been signed up") } }