我不必每次都对您的 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();
}
}