[英]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那会
/**
* 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.