使用适用于 Java 2.x 的 SDK 的亚马逊 Cognito 身份提供商示例 - AWS SDK for Java 2.x

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

使用适用于 Java 2.x 的 SDK 的亚马逊 Cognito 身份提供商示例

以下代码示例向您展示了如何使用AWS SDK for Java 2.x带有 Amazon Cognito 身份提供商的操作和实现常见场景。

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

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

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

操作

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

public static void confirmSignUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String code, String userName) { try { ConfirmSignUpRequest signUpRequest = ConfirmSignUpRequest.builder() .clientId(clientId) .confirmationCode(code) .username(userName) .build(); identityProviderClient.confirmSignUp(signUpRequest); System.out.println(userName +" was confirmed"); } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

public static String getSecretForAppMFA(CognitoIdentityProviderClient identityProviderClient, String session) { AssociateSoftwareTokenRequest softwareTokenRequest = AssociateSoftwareTokenRequest.builder() .session(session) .build(); AssociateSoftwareTokenResponse tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest) ; String secretCode = tokenResponse.secretCode(); System.out.println("Enter this token into Google Authenticator"); System.out.println(secretCode); return tokenResponse.session(); }

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

public static void getAdminUser(CognitoIdentityProviderClient identityProviderClient, String userName, String poolId) { try { AdminGetUserRequest userRequest = AdminGetUserRequest.builder() .username(userName) .userPoolId(poolId) .build(); AdminGetUserResponse response = identityProviderClient.adminGetUser(userRequest); System.out.println("User status "+response.userStatusAsString()); } catch (CognitoIdentityProviderException e){ System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

public static void listAllUsers(CognitoIdentityProviderClient cognitoClient, String userPoolId ) { try { ListUsersRequest usersRequest = ListUsersRequest.builder() .userPoolId(userPoolId) .build(); ListUsersResponse response = cognitoClient.listUsers(usersRequest); response.users().forEach(user -> { System.out.println("User " + user.username() + " Status " + user.userStatus() + " Created " + user.userCreateDate() ); }); } catch (CognitoIdentityProviderException e){ System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // Shows how to list users by using a filter. public static void listUsersFilter(CognitoIdentityProviderClient cognitoClient, String userPoolId ) { try { String filter = "email = \"tblue@noserver.com\""; ListUsersRequest usersRequest = ListUsersRequest.builder() .userPoolId(userPoolId) .filter(filter) .build(); ListUsersResponse response = cognitoClient.listUsers(usersRequest); response.users().forEach(user -> { System.out.println("User with filter applied " + user.username() + " Status " + user.userStatus() + " Created " + user.userCreateDate() ); }); } catch (CognitoIdentityProviderException e){ System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

public static void resendConfirmationCode(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName) { try { ResendConfirmationCodeRequest codeRequest = ResendConfirmationCodeRequest.builder() .clientId(clientId) .username(userName) .build(); ResendConfirmationCodeResponse response = identityProviderClient.resendConfirmationCode(codeRequest); System.out.println("Method of delivery is "+response.codeDeliveryDetails().deliveryMediumAsString()); } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

以下代码示例显示了如何响应 Amazon Cognito 身份验证挑战。

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

// Respond to an authentication challenge. public static void adminRespondToAuthChallenge(CognitoIdentityProviderClient identityProviderClient, String userName, String clientId, String mfaCode, String session) { System.out.println("SOFTWARE_TOKEN_MFA challenge is generated"); Map<String, String> challengeResponses = new HashMap<>(); challengeResponses.put("USERNAME", userName); challengeResponses.put("SOFTWARE_TOKEN_MFA_CODE", mfaCode); AdminRespondToAuthChallengeRequest respondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest.builder() .challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA) .clientId(clientId) .challengeResponses(challengeResponses) .session(session) .build(); AdminRespondToAuthChallengeResponse respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(respondToAuthChallengeRequest); System.out.println("respondToAuthChallengeResult.getAuthenticationResult()" + respondToAuthChallengeResult.authenticationResult()); }

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

public static void signUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, String password, String email) { AttributeType userAttrs = AttributeType.builder() .name("email") .value(email) .build(); List<AttributeType> userAttrsList = new ArrayList<>(); userAttrsList.add(userAttrs); try { SignUpRequest signUpRequest = SignUpRequest.builder() .userAttributes(userAttrsList) .username(userName) .clientId(clientId) .password(password) .build(); identityProviderClient.signUp(signUpRequest); System.out.println("User has been signed up "); } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

public static AdminInitiateAuthResponse initiateAuth(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, String password, String userPoolId) { try { Map<String,String> authParameters = new HashMap<>(); authParameters.put("USERNAME", userName); authParameters.put("PASSWORD", password); AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder() .clientId(clientId) .userPoolId(userPoolId) .authParameters(authParameters) .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH) .build(); AdminInitiateAuthResponse response = identityProviderClient.adminInitiateAuth(authRequest); System.out.println("Result Challenge is : " + response.challengeName() ); return response; } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; }

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

// Verify the TOTP and register for MFA. public static void verifyTOTP(CognitoIdentityProviderClient identityProviderClient, String session, String code) { try { VerifySoftwareTokenRequest tokenRequest = VerifySoftwareTokenRequest.builder() .userCode(code) .session(session) .build(); VerifySoftwareTokenResponse verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest); System.out.println("The status of the token is " +verifyResponse.statusAsString()); } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

场景

以下代码示例显示了如何:

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

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

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

SDK for Java 2.x
注意

还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/** * Before running this Java V2 code example, set up your development environment, including your credentials. * * For more information, see the following documentation: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.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 AdminInitiateAuth 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. */ public class CognitoMVP { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException { final String usage = "\n" + "Usage:\n" + " <clientId> <poolId>\n\n" + "Where:\n" + " clientId - The app client Id value that you can get from the AWS CDK script.\n\n" + " poolId - The pool Id that you can get from the AWS CDK script. \n\n" ; if (args.length != 2) { System.out.println(usage); System.exit(1); } String clientId = args[0]; String poolId = args[1]; CognitoIdentityProviderClient identityProviderClient = CognitoIdentityProviderClient.builder() .region(Region.US_EAST_1) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon Cognito example scenario."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("*** Enter your user name"); Scanner in = new Scanner(System.in); String userName = in.nextLine(); System.out.println("*** Enter your password"); String password = in.nextLine(); System.out.println("*** Enter your email"); String email = in.nextLine(); System.out.println("1. Signing up " + userName); signUp(identityProviderClient, clientId, userName, password, email); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Getting " + userName + " in the user pool"); getAdminUser(identityProviderClient, userName, poolId); System.out.println("*** Conformation code sent to " + userName + ". Would you like to send a new code? (Yes/No)"); System.out.println(DASHES); System.out.println(DASHES); String ans = in.nextLine(); if (ans.compareTo("Yes") == 0) { resendConfirmationCode(identityProviderClient, clientId, userName); System.out.println("3. Sending a new confirmation code"); } System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Enter confirmation code that was emailed"); String code = in.nextLine(); confirmSignUp(identityProviderClient, clientId, code, userName); System.out.println("Rechecking the status of " + userName + " in the user pool"); getAdminUser(identityProviderClient, userName, poolId); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Invokes the initiateAuth to sign in"); AdminInitiateAuthResponse authResponse = initiateAuth(identityProviderClient, clientId, userName, password, poolId) ; String mySession = authResponse.session() ; System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Invokes the AssociateSoftwareToken method to generate a TOTP key"); String newSession = getSecretForAppMFA(identityProviderClient, mySession); System.out.println(DASHES); System.out.println(DASHES); System.out.println("*** Enter the 6-digit code displayed in Google Authenticator"); String myCode = in.nextLine(); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Verify the TOTP and register for MFA"); verifyTOTP(identityProviderClient, newSession, myCode); System.out.println(DASHES); System.out.println(DASHES); System.out.println("8. Re-enter a 6-digit code displayed in Google Authenticator"); String mfaCode = in.nextLine(); AdminInitiateAuthResponse authResponse1 = initiateAuth(identityProviderClient, clientId, userName, password, poolId); System.out.println(DASHES); System.out.println(DASHES); System.out.println("9. Invokes the AdminRespondToAuthChallenge"); String session2 = authResponse1.session(); adminRespondToAuthChallenge(identityProviderClient, userName, clientId, mfaCode, session2); System.out.println(DASHES); System.out.println(DASHES); System.out.println("All Amazon Cognito operations were successfully performed"); System.out.println(DASHES); } // Respond to an authentication challenge. public static void adminRespondToAuthChallenge(CognitoIdentityProviderClient identityProviderClient, String userName, String clientId, String mfaCode, String session) { System.out.println("SOFTWARE_TOKEN_MFA challenge is generated"); Map<String, String> challengeResponses = new HashMap<>(); challengeResponses.put("USERNAME", userName); challengeResponses.put("SOFTWARE_TOKEN_MFA_CODE", mfaCode); AdminRespondToAuthChallengeRequest respondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest.builder() .challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA) .clientId(clientId) .challengeResponses(challengeResponses) .session(session) .build(); AdminRespondToAuthChallengeResponse respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(respondToAuthChallengeRequest); System.out.println("respondToAuthChallengeResult.getAuthenticationResult()" + respondToAuthChallengeResult.authenticationResult()); } // Verify the TOTP and register for MFA. public static void verifyTOTP(CognitoIdentityProviderClient identityProviderClient, String session, String code) { try { VerifySoftwareTokenRequest tokenRequest = VerifySoftwareTokenRequest.builder() .userCode(code) .session(session) .build(); VerifySoftwareTokenResponse verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest); System.out.println("The status of the token is " +verifyResponse.statusAsString()); } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static AdminInitiateAuthResponse initiateAuth(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, String password, String userPoolId) { try { Map<String,String> authParameters = new HashMap<>(); authParameters.put("USERNAME", userName); authParameters.put("PASSWORD", password); AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder() .clientId(clientId) .userPoolId(userPoolId) .authParameters(authParameters) .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH) .build(); AdminInitiateAuthResponse response = identityProviderClient.adminInitiateAuth(authRequest); System.out.println("Result Challenge is : " + response.challengeName() ); return response; } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } public static String getSecretForAppMFA(CognitoIdentityProviderClient identityProviderClient, String session) { AssociateSoftwareTokenRequest softwareTokenRequest = AssociateSoftwareTokenRequest.builder() .session(session) .build(); AssociateSoftwareTokenResponse tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest) ; String secretCode = tokenResponse.secretCode(); System.out.println("Enter this token into Google Authenticator"); System.out.println(secretCode); return tokenResponse.session(); } public static void confirmSignUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String code, String userName) { try { ConfirmSignUpRequest signUpRequest = ConfirmSignUpRequest.builder() .clientId(clientId) .confirmationCode(code) .username(userName) .build(); identityProviderClient.confirmSignUp(signUpRequest); System.out.println(userName +" was confirmed"); } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void resendConfirmationCode(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName) { try { ResendConfirmationCodeRequest codeRequest = ResendConfirmationCodeRequest.builder() .clientId(clientId) .username(userName) .build(); ResendConfirmationCodeResponse response = identityProviderClient.resendConfirmationCode(codeRequest); System.out.println("Method of delivery is "+response.codeDeliveryDetails().deliveryMediumAsString()); } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void signUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, String password, String email) { AttributeType userAttrs = AttributeType.builder() .name("email") .value(email) .build(); List<AttributeType> userAttrsList = new ArrayList<>(); userAttrsList.add(userAttrs); try { SignUpRequest signUpRequest = SignUpRequest.builder() .userAttributes(userAttrsList) .username(userName) .clientId(clientId) .password(password) .build(); identityProviderClient.signUp(signUpRequest); System.out.println("User has been signed up "); } catch(CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void getAdminUser(CognitoIdentityProviderClient identityProviderClient, String userName, String poolId) { try { AdminGetUserRequest userRequest = AdminGetUserRequest.builder() .username(userName) .userPoolId(poolId) .build(); AdminGetUserResponse response = identityProviderClient.adminGetUser(userRequest); System.out.println("User status "+response.userStatusAsString()); } catch (CognitoIdentityProviderException e){ System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }