JAVA- AWS Cognito - 检查用户是否存在于 Cognito 用户池中

JAVA- AWS Cognito -Check if a user exists in Cognito User pool

我想允许用户在字段中输入他们的 username/password。继续后,我想 运行 检查该用户是否已存在于用户池中。如果他们这样做,请让他们登录并继续使用应用程序,如果他们没有,请转到帐户创建流程,他们将被指示添加姓名、phone 号码、电子邮件等。

我找不到有关如何使用 AWS Cognito 登录用户的文档。我应该能够在通话中传递 username/passcode 并得到回复说用户 Exists/User 不存在或其他任何内容!我在这里遗漏了什么吗?

如有任何帮助,我们将不胜感激。我已经搜索了文档...

要列出用户,您可以使用 AWS Java SDK:

public static void list() {
    AwsBasicCredentials awsCreds = AwsBasicCredentials.create(AWS_KEY,
            AWS_SECRET);

    CognitoIdentityProviderClient identityProviderClient =
            CognitoIdentityProviderClient.builder()
                    .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
                    .region(Region.of(REGION))
                    .build();

    final ListUsersRequest listUsersRequest = ListUsersRequest.builder()
            .userPoolId(POOL_ID)
            .build();

    ListUsersResponse result = identityProviderClient.listUsers(listUsersRequest);

    System.out.println("Has users:"+result.hasUsers());
    result.users().stream().map(u->u.username()).forEach(System.out::println);
}

需要下一个依赖(请使用最新版本):

<dependency>
  <groupId>software.amazon.awssdk</groupId>
  <artifactId>aws-core</artifactId>
  <version>2.13.57</version>
</dependency>

<dependency>
  <groupId>software.amazon.awssdk</groupId>
  <artifactId>cognitoidentityprovider</artifactId>
  <version>2.13.57</version>
</dependency>

Here 是如何从 Java.

登录用户的代码示例

我不必每次都对您的 Cognito 用户池进行全面扫描,而是使用 Cognito 的功能来触发事件。对于您的用例,Cognito 可以 运行 Lambda。您对 Migrate User 触发器感兴趣。基本上发生的事情是,当用户尝试通过 Cognito and 登录到您的系统时,池中不存在该用户,触发一个触发器让您登录该用户并迁移他们到 Cognito。

传入的数据如下所示:

{
    "version": "1",
    "triggerSource": "UserMigration_Authentication",
    "region": "us-west-2",
    "userPoolId": "us-west-2_abcdef",
    "userName": "theusername@example.com",
    "callerContext": {
        "awsSdkVersion": "aws-sdk-unknown-unknown",
        "clientId": "yourclientid"
    },
    "request": {
        "password": "theuserpassword",
        "validationData": null,
        "userAttributes": null
    },
    "response": {
        "userAttributes": null,
        "forceAliasCreation": null,
        "finalUserStatus": null,
        "messageAction": null,
        "desiredDeliveryMediums": null
    }
}

您的 Lambda 将使用它并最终获取用户名和密码并确定其是否有效。如果是,您将传回 response.userAttributes 字段中的信息以及您是否要发送 Cognito 欢迎电子邮件 (messageAction) 和其他一些值。例如,您可以发回:

{
    "version": "1",
    "triggerSource": "UserMigration_Authentication",
    "region": "us-west-2",
    "userPoolId": "us-west-2_abcdef",
    "userName": "theusername@example.com",
    "callerContext": {
        "awsSdkVersion": "aws-sdk-unknown-unknown",
        "clientId": "yourclientid"
    },
    "request": {
        "password": "theuserpassword",
        "validationData": null,
        "userAttributes": null
    },
    "response": {
        "userAttributes": { "email":"theusername@example.com",
                            "email_verified": "true" }
        "forceAliasCreation": null,
        "finalUserStatus": "CONFIRMED",
        "messageAction": "SUPPRESS",
        "desiredDeliveryMediums": null
    }
}

您的 Lambda 在 Java 中看起来像这样:

public class MigrateUserLambda implements RequestStreamHandler {

    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        LambdaLogger logger = context.getLogger();

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(inputStream);

        logger.log("input is " + objectMapper.writeValueAsString(rootNode));

        String email = rootNode.path("email").asText();
        String password = rootNode.path("request").path("password").asText();

        // verify user name and password in MySQL.  If ok...

        String triggerSource = rootNode.path("triggerSource").asText();

        if( triggerSource.equals("UserMigration_Authentication")) {
            JsonNode responseNode = rootNode.path("response");
            if (responseNode != null) {
                ((ObjectNode) responseNode).with("userAttributes").put("username", "theusername@example.com" );
                ((ObjectNode) responseNode).with("userAttributes").put("email_verified", "true" );
                ((ObjectNode) responseNode).put("messageAction", "SUPPRESS");
                ((ObjectNode) responseNode).put("finalUserStatus", "CONFIRMED");
            }
        }

        String output = objectMapper.writeValueAsString(rootNode);

        OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
        writer.write(output);
        logger.log("sending back " + output);

        writer.close();
    }
}

要检查用户是否存在,您只需要用户名。

因此对于您的场景,在用户输入用户名和密码后触发下面的 myMethod()。那将

  1. 检查用户名是否已经在用户
  2. 如果用户名存在,则执行登录
  3. 如果用户名不存在,创建账户

/**
* let's say you call this method when user enters username and password
* @param context context
* @param identityProvider cognito client
* @param username user entered username
* @param password user entered password
* @return
*/
private void myMethod(Context context, AWSCognitoIdentityProvider identityProvider, String username, String password) {
    
    boolean userExists = userExists(context, identityProvider, username);
    
    if(userExists) {
        // perform sign in with provided password
    } else {
        // create account
    }
}


/**
* @param context context
* @param identityProvider cognito client
* @param username user entered username
* @return true if username is already in use, false otherwise
*/
private boolean userExists(Context context, AWSCognitoIdentityProvider identityProvider, String username) {
    LambdaLogger logger = context.getLogger();

    try {
        AdminGetUserRequest getUserRequest = new AdminGetUserRequest();
        getUserRequest.setUserPoolId("cognitoPoolId");
        getUserRequest.setUsername(username);

        AdminGetUserResult getUserResult = identityProvider.adminGetUser(getUserRequest);

        return true;
    } catch (UserNotFoundException userNotFoundException) {
        logger.log("UserNotFoundException! " + userNotFoundException.toString());
        return false;
    } catch (Exception e) {
        return false;
    }
}