Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 
      中国的 Amazon Web Services 服务入门
         (PDF)。
    本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
注册前 Lambda 触发器
您可能想要在具有自助注册选项的用户池中自定义注册流程。注册前触发器的一些常见用途包括对新用户进行自定义分析和记录、应用安全和治理标准,或者将第三方 IdP 的用户链接到整合的用户配置文件。您可能还有不需要进行验证和确认的可信用户。
在 Amazon Cognito 完成新本地用户或联合用户创建之前,它会立即激活注册前 Lambda 函数。发送到此函数的请求对象userAttributes中包含由本地用户注册提供的属性或已成功从联合用户的提供者属性映射出来的属性。在使用可信身份提供商进行自助注册SignUp或首次登录时,以及使用创建用户时,您的用户池会调用此触发器。AdminCreateUser在注册过程中,您可以使用此函数,利用自定义逻辑来分析登录事件,并修改或拒绝新用户。
        注册前 Lambda 触发器参数
        Amazon Cognito 传递给此 Lambda 函数的请求是以下参数和 Amazon Cognito 添加到所有请求中的常用参数的组合。
        
            - JSON
- 
                    {
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        },
        "validationData": {
            "string": "string",
            . . .
         },
        "clientMetadata": {
            "string": "string",
            . . .
         }
    },
    "response": {
        "autoConfirmUser": "boolean",
        "autoVerifyPhone": "boolean",
        "autoVerifyEmail": "boolean"
    }
}
 
注册前请求参数
            
                 
                 
                 
            
                    - userAttributes
- 
                        表示用户属性的一个或多个名称/值对。属性名称是键。 
- validationData
- 
                        一个或多个包含用户属性数据的键值对,您的应用程序在创建新用户的请求中将这些数据传递给 Amazon Cognito。在您AdminCreateUser或 SignUpAPI 请求的 ValidationData 参数中将此信息发送到您的 Lambda 函数。 Amazon Cognito 不会将你的 ValidationData 数据设置为你创建的用户的属性。  ValidationData 是您为注册前 Lambda 触发器而提供的临时用户信息。 
- clientMetadata
- 
                        一个或多个键值对,您可以将其作为自定义输入内容提供给为注册前触发器指定的 Lambda 函数。您可以使用以下 API 操作中的 ClientMetadata参数将此数据传递给您的 Lambda 函数:AdminCreateUser、AdminRespondToAuthChallengeForgotPassword、和。SignUp 
 
         
         
            注册前响应参数
            在响应中,如果您想要自动确认用户,则您可以将 autoConfirmUser 设置为 true。您可以将 autoVerifyEmail 设置为 true,以自动验证用户的电子邮件。您可以将 autoVerifyPhone 设置为 true,以自动验证用户的电话号码。
            AdminCreateUser API 触发注册前 Lambda 函数时,Amazon Cognito 会忽略响应参数 autoVerifyPhone、autoVerifyEmail 和 autoConfirmUser。
                 
                 
                 
            
                    - autoConfirmUser
- 
                        设置为 true以自动确认用户,否则设置为false。
 
- autoVerifyEmail
- 
                        设置为 true可以设置为所注册用户已通过验证的电子邮件地址,否则为false。如果autoVerifyEmail设置为true,则email属性必须具有有效的非空值。否则将出现错误,用户将无法完成注册。
 如果选择 email属性作为别名,则在设置了autoVerifyEmail时将为用户的电子邮件地址创建别名。如果已存在具有该电子邮件地址的别名,则别名将移动到新用户,以前用户的电子邮件地址将标记为未验证。有关更多信息,请参阅 自定义登录属性。
 
- autoVerifyPhone
- 
                        设置为 true可以设置为所注册用户已通过验证的电话号码,否则为false。如果autoVerifyPhone设置为true,则phone_number属性必须具有有效的非空值。否则将出现错误,用户将无法完成注册。
 如果选择 phone_number属性作为别名,则在设置了autoVerifyPhone时将为用户的电话号码创建别名。如果已存在具有该电话号码的别名,则别名将移动到新用户,以前用户的电话号码将标记为未验证。有关更多信息,请参阅 自定义登录属性。
 
 
         
     
        注册前示例:从注册的域自动确认用户
        这是示例 Lambda 触发器代码。在 Amazon Cognito 处理注册请求之前,会立即调用注册前触发器。它使用自定义属性 custom:domain 自动确认来自特定电子邮件域的新用户。任何不在自定义域中的新用户都将添加到用户池,但不会自动确认。
        
            - Node.js
- 
                    export const handler = async (event, context, callback) => {
  // Set the user pool autoConfirmUser flag after validating the email domain
  event.response.autoConfirmUser = false;
  // Split the email address so we can compare domains
  var address = event.request.userAttributes.email.split("@");
  // This example uses a custom attribute "custom:domain"
  if (event.request.userAttributes.hasOwnProperty("custom:domain")) {
    if (event.request.userAttributes["custom:domain"] === address[1]) {
      event.response.autoConfirmUser = true;
    }
  }
  // Return to Amazon Cognito
  callback(null, event);
};
 
- Python
- 
                    def lambda_handler(event, context):
    # It sets the user pool autoConfirmUser flag after validating the email domain
    event['response']['autoConfirmUser'] = False
    # Split the email address so we can compare domains
    address = event['request']['userAttributes']['email'].split('@')
    # This example uses a custom attribute 'custom:domain'
    if 'custom:domain' in event['request']['userAttributes']:
        if event['request']['userAttributes']['custom:domain'] == address[1]:
            event['response']['autoConfirmUser'] = True
    # Return to Amazon Cognito
    return event
 
Amazon Cognito 将事件信息传递给 Lambda 函数。随后,该函数将相同事件对象随同响应中的任何更改返回给 Amazon Cognito。在 Lambda 控制台中,您可以设置一个测试事件,该事件包含与您的 Lambda 触发器相关的数据。以下是此代码示例的一个测试事件:
        
            - JSON
- 
                    {
    "request": {
        "userAttributes": {
            "email": "testuser@example.com",
            "custom:domain": "example.com"
        }
    },
    "response": {}
}
 
注册前示例:自动确认和自动验证所有用户
        此示例确认所有用户并将用户的 email 和 phone_number 属性设置为“已验证”(如果该属性存在)。此外,如果启用了别名,当设置了自动验证时,将为 phone_number 和 email 创建别名。
        如果已存在具有相同电话号码的别名,则别名将移动到新用户,以前用户的 phone_number 将标记为未验证。电子邮件地址也是如此。为了防止这种情况发生,您可以使用用户池 ListUsers API 来查看是否有现有用户已在使用新用户的电话号码或电子邮件地址作为别名。
            - Node.js
- 
                    exports.handler = (event, context, callback) => {
  // Confirm the user
  event.response.autoConfirmUser = true;
  // Set the email as verified if it is in the request
  if (event.request.userAttributes.hasOwnProperty("email")) {
    event.response.autoVerifyEmail = true;
  }
  // Set the phone number as verified if it is in the request
  if (event.request.userAttributes.hasOwnProperty("phone_number")) {
    event.response.autoVerifyPhone = true;
  }
  // Return to Amazon Cognito
  callback(null, event);
};
 
- Python
- 
                    def lambda_handler(event, context):
    # Confirm the user
    event['response']['autoConfirmUser'] = True
    # Set the email as verified if it is in the request
    if 'email' in event['request']['userAttributes']:
        event['response']['autoVerifyEmail'] = True
    # Set the phone number as verified if it is in the request
    if 'phone_number' in event['request']['userAttributes']:
        event['response']['autoVerifyPhone'] = True
    # Return to Amazon Cognito
    return event
 
Amazon Cognito 将事件信息传递给 Lambda 函数。随后,该函数将相同事件对象随同响应中的任何更改返回给 Amazon Cognito。在 Lambda 控制台中,您可以设置一个测试事件,该事件包含与您的 Lambda 触发器相关的数据。以下是此代码示例的一个测试事件:
        
            - JSON
- 
                    {
  "request": {
    "userAttributes": {
      "email": "user@example.com",
      "phone_number": "+12065550100"
    }
  },
  "response": {}
}
 
注册前示例:如果用户名少于五个字符,则拒绝注册
        此示例检查注册请求中用户名的长度。如果用户输入的名称长度少于五个字符,则该示例将返回错误。
        
            - Node.js
- 
                    export const handler = (event, context, callback) => {
    // Impose a condition that the minimum length of the username is 5 is imposed on all user pools.
    if (event.userName.length < 5) {
        var error = new Error("Cannot register users with username less than the minimum length of 5");
        // Return error to Amazon Cognito
        callback(error, event);
    }
    // Return to Amazon Cognito
    callback(null, event);
};
 
- Python
- 
                    def lambda_handler(event, context):
    if len(event['userName']) < 5:
        raise Exception("Cannot register users with username less than the minimum length of 5")
    # Return to Amazon Cognito
    return event
 
Amazon Cognito 将事件信息传递给 Lambda 函数。随后,该函数将相同事件对象随同响应中的任何更改返回给 Amazon Cognito。在 Lambda 控制台中,您可以设置一个测试事件,该事件包含与您的 Lambda 触发器相关的数据。以下是此代码示例的一个测试事件:
        
            - JSON
- 
                    {
  "userName": "rroe",
  "response": {}
}