我希望允许用户在字段中输入其用户名/密码。继续后,我要运行检查以查看该用户池中是否已存在该用户。如果是这样,请登录并继续使用应用程序;如果没有,请转到帐户创建流程,系统将指示他们添加姓名,电话号码,电子邮件等。
我找不到有关如何使用AWS Cognito登录用户的文档。我应该能够在通话中传递用户名/密码,并得到响应,说用户不存在/用户不存在或任何其他原因!我在这里想念东西吗?
任何帮助将不胜感激。我已经搜索了文档...
答案 0 :(得分:1)
要检查用户是否存在,只需输入用户名即可。
因此,对于您的情况,在用户输入用户名和密码后触发以下myMethod()
。那会
/**
* 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;
}
}
答案 1 :(得分:0)
我不必每次都对Cognito用户池进行全面扫描,而是使用Cognito的功能来触发事件。对于您的用例,Cognito可以运行Lambda。您对Migrate User触发器感兴趣。基本上发生的是,当用户尝试通过Cognito 登录到系统并且该池中不存在该用户时,将触发一个触发器,让您登录该用户并将其迁移到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();
}
}
答案 2 :(得分:-1)
要列出用户,您可以使用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登录用户的代码示例。