

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 注册前 Lambda 触发器
<a name="user-pool-lambda-pre-sign-up"></a>

您可能想要在具有自助注册选项的用户池中自定义注册流程。注册前触发器的一些常见用途包括对新用户进行自定义分析和记录、应用安全和治理标准，或者将第三方 IdP 的用户链接到[整合的用户配置文件](cognito-user-pools-identity-federation-consolidate-users.md)。您可能还有不需要进行[验证和确认](signing-up-users-in-your-app.md)的可信用户。

在 Amazon Cognito 完成创建新的[本地](cognito-terms.md#terms-localuser)用户或[联合](cognito-terms.md#terms-federateduser)用户之前不久，它会激活注册前 Lambda 函数。发送给此函数的请求对象中的 `userAttributes` 包含本地用户注册时提供的属性，或已成功从联合用户的身份提供者属性映射过来的属性。在使用可信[身份提供商](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-federated)进行自助注册[SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html)或首次登录时，以及使用创建用户时，您的用户池会调用此触发器。[AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html)在注册过程中，您可以使用此函数，利用自定义逻辑来分析登录事件，并修改或拒绝新用户。

**Topics**
+ [注册前 Lambda 触发器参数](#cognito-user-pools-lambda-trigger-syntax-pre-signup)
+ [注册前示例：从注册的域自动确认用户](#aws-lambda-triggers-pre-registration-example)
+ [注册前示例：自动确认和自动验证所有用户](#aws-lambda-triggers-pre-registration-example-2)
+ [注册前示例：如果用户名少于五个字符，则拒绝注册](#aws-lambda-triggers-pre-registration-example-3)

## 注册前 Lambda 触发器参数
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup"></a>

Amazon Cognito 传递给此 Lambda 函数的请求是以下参数和 Amazon Cognito 添加到所有请求中的[常用参数](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared)的组合。

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        },
        "validationData": {
            "string": "string",
            . . .
         },
        "clientMetadata": {
            "string": "string",
            . . .
         }
    },

    "response": {
        "autoConfirmUser": "boolean",
        "autoVerifyPhone": "boolean",
        "autoVerifyEmail": "boolean"
    }
}
```

------

### 注册前请求参数
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup-request"></a>

**userAttributes**  
表示用户属性的一个或多个名称/值对。属性名称是键。

**validationData**  
一个或多个包含用户属性数据的键值对，您的应用程序在创建新用户的请求中将这些数据传递给 Amazon Cognito。在您[AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html)或 [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html)API 请求的 ValidationData 参数中将此信息发送到您的 Lambda 函数。  
Amazon Cognito 不会将你的 ValidationData 数据设置为你创建的用户的属性。 ValidationData 是您为注册前 Lambda 触发器而提供的临时用户信息。

**clientMetadata**  
一个或多个键值对，您可以将其作为自定义输入内容提供给为注册前触发器指定的 Lambda 函数。您可以使用以下 API 操作中的 ClientMetadata参数将此数据传递给您的 Lambda 函数：[AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html)、[AdminRespondToAuthChallenge[ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html)](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html)、和。[SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html)

### 注册前响应参数
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup-response"></a>

在响应中，如果您想要自动确认用户，则您可以将 `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` 时将为用户的电子邮件地址创建别名。如果已存在具有该电子邮件地址的别名，则别名将移动到新用户，以前用户的电子邮件地址将标记为未验证。有关更多信息，请参阅 [自定义登录属性](user-pool-settings-attributes.md#user-pool-settings-aliases)。

**autoVerifyPhone**  
设置为 `true` 可以设置为所注册用户已通过验证的电话号码，否则为 `false`。如果 `autoVerifyPhone` 设置为 `true`，则 `phone_number` 属性必须具有有效的非空值。否则将出现错误，用户将无法完成注册。  
如果选择 `phone_number` 属性作为别名，则在设置了 `autoVerifyPhone` 时将为用户的电话号码创建别名。如果已存在具有该电话号码的别名，则别名将移动到新用户，以前用户的电话号码将标记为未验证。有关更多信息，请参阅 [自定义登录属性](user-pool-settings-attributes.md#user-pool-settings-aliases)。

## 注册前示例：从注册的域自动确认用户
<a name="aws-lambda-triggers-pre-registration-example"></a>

这是 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": {}
}
```

------

## 注册前示例：自动确认和自动验证所有用户
<a name="aws-lambda-triggers-pre-registration-example-2"></a>

此示例确认所有用户并将用户的 `email` 和 `phone_number` 属性设置为“已验证”（如果该属性存在）。此外，如果启用了别名，当设置了自动验证时，将为 `phone_number` 和 `email` 创建别名。

**注意**  
如果已存在具有相同电话号码的别名，则别名将移动到新用户，以前用户的 `phone_number` 将标记为未验证。电子邮件地址也是如此。为了防止这种情况发生，您可以使用用户池 [ListUsers API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html) 来查看是否有现有用户已在使用新用户的电话号码或电子邮件地址作为别名。

------
#### [ 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": {}
}
```

------

## 注册前示例：如果用户名少于五个字符，则拒绝注册
<a name="aws-lambda-triggers-pre-registration-example-3"></a>

此示例检查注册请求中用户名的长度。如果用户输入的名称长度少于五个字符，则该示例将返回错误。

------
#### [ 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": {}
}
```

------