简体   繁体   English

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

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

I want to allow a user to enter their username/password in a field.我想允许用户在字段中输入他们的用户名/密码。 Upon continuing, I want to run a check to see if that user already exists in the user pool.继续后,我想运行检查以查看该用户是否已存在于用户池中。 If they do, log them in and continue with app, if they do not, move to account creation flow where they will be instructed to add name, phone number, email etc.如果他们这样做,请登录并继续使用应用程序,如果他们不这样做,则转到帐户创建流程,在那里他们将被指示添加姓名、电话号码、电子邮件等。

I cannot find documentation on how to log a user in using AWS Cognito.我找不到有关如何使用 AWS Cognito 登录用户的文档。 I should be able to pass username/passcode in a call and get a response back that says User Exists/User does not exist or whatever!我应该能够在通话中传递用户名/密码并得到回复,说用户存在/用户不存在或其他什么! Am I missing something here?我在这里错过了什么吗?

Any help would be greatly appreciated.任何帮助将不胜感激。 I've scoured the documentation...我已经搜索了文档...

To check if the user exists or not, all you need is username.要检查用户是否存在,您只需要用户名即可。

So for your scenario, trigger the myMethod() below after user enters username and password.因此,对于您的场景,在用户输入用户名和密码后触发下面的myMethod() That will那会

  1. Check if the username is already in user检查用户名是否已经在 user 中
  2. If username exists, perform sign in如果用户名存在,则执行登录
  3. If username does not exists, create account如果用户名不存在,则创建帐户

/**
* 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;
    }
}

Instead of having to do a full scan of your Cognito user pool every time, I'd use the ability of Cognito to trigger an event.我不必每次都对 Cognito 用户池进行全面扫描,而是使用 Cognito 的功能来触发事件。 For your use case Cognito can run a Lambda.对于您的用例,Cognito 可以运行 Lambda。 You're interested in the Migrate User trigger.您对迁移用户触发器感兴趣。 Basically what happens is that when the user tries to log into your system through Cognito and the user doesn't exist in the pool, a trigger is fired to let you log the user in and migrate them to Cognito.基本上发生的情况是,当用户尝试通过 Cognito 登录您的系统并且该用户不存在于池中时,将触发触发器以让您登录用户并将其迁移到 Cognito。

The data coming in looks like:传入的数据如下所示:

{
    "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
    }
}

Your Lambda will consume this and ultimately take the username and password and determine if it is valid.您的 Lambda 将使用它并最终获取用户名和密码并确定它是否有效。 If it is, you will pass back information in the response.userAttributes field along with things like if you want to send a Cognito welcome email ( messageAction ) and some other values.如果是,您将在response.userAttributes字段中传回信息以及是否要发送 Cognito 欢迎电子邮件 ( messageAction ) 和其他一些值。 For example, you may send back:例如,您可以发回:

{
    "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
    }
}

Your Lambda will look something like this in Java:你的 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();
    }
}

To list users you can use AWS Java SDK:要列出用户,您可以使用 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);
}

it requires next dependecies (please use latest versions):它需要下一个依赖项(请使用最新版本):

<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 is a code sample of how to login user from Java. 是如何从 Java 登录用户的代码示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查用户是否已登录AWS Cognito,JAVA - Check if user is logged in aws cognito, JAVA 如何以编程方式为 Java 中 AWS Cognito 用户池中的登录用户启用或禁用 MFA? - How to programmatically enable or disable MFA for a logged user in AWS Cognito user pool in Java? Cognito 用户池:在 aws cognito java sdk 中 accessToken 过期后,如何使用 refreshToken 获取新的 accessToken? - Cognito user pool: How to use refreshToken to get new accessToken after accessToken gets expired in aws cognito java sdk? 用户身份池使用Amazon Cognito对用户进行身份验证-Java SDK - User Identity Pool Authenticate user with Amazon Cognito - Java SDK 与Cognito用户池集成后如何访问AWS API - How to access AWS API after integrated with cognito user pool 带有 Spring Boot 的 AWS Cognito 用户池服务器端流程 - AWS cognito user pool server side flow with spring boot 适用于通过Cognito用户池为Oauth客户端凭据流身份验证提供服务的AWS Java SDK吗? - AWS Java SDK for service to service Oauth client credentential flow authentication with Cognito user pool? 如何使用Java将用户注册到Amazon Cognito身份用户池 - How to register users to Amazon Cognito identity user pool by using Java Java:未经授权执行sts:AssumeRoleWithWebIdentity认知用户池 - Java:Not authorized to perform sts:AssumeRoleWithWebIdentity cognito user pool AWS Cognito 用户设备触发器 - AWS Cognito User Devices Trigger
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM