

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# サインアップ前の 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` には、ローカルユーザーのサインアップ時に指定した属性、またはフェデレーションユーザーのプロバイダー属性から正常にマッピングされた属性が含まれています。ユーザープールは、[SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) によるセルフサービスのサインアップ時や信頼できる [ID プロバイダー](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-federated)による初回サインイン時、および [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)
+ [サインアップ前の例:ユーザー名が 5 文字未満の場合にサインアップを拒否する](#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**  
ユーザー属性を表す 1 つ以上の名前 - 値ペア。属性名はキーです。

**validationData**  
新しいユーザーの作成リクエストでアプリケーションから Amazon Cognito に渡したユーザー属性データを示す 1 つ以上のキーと値のペアです。この情報を [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) API リクエストまたは [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 関数へのカスタム入力として提供できる 1 つ、または複数のキー/値ペア。このデータは、[AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html)、[AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html)、[ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html)、および [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) の API アクションで ClientMetadata パラメータを使用することによって Lambda 関数に渡すことができます。

### サインアップ前のレスポンスパラメータ
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup-response"></a>

ユーザーを自動的に確認する場合は、レスポンスで `autoConfirmUser` を `true` に設定できます。`autoVerifyEmail` を `true` に設定してユーザーの E メールを自動検証できます。`autoVerifyPhone` を `true` に設定してユーザーの電話番号を自動検証できます。

**注記**  
サインアップ前 Lambda 関数が `AdminCreateUser` API によってトリガーされる場合、レスポンスパラメータの `autoVerifyPhone`、`autoVerifyEmail`、および `autoConfirmUser` は Amazon Cognito によって無視されます。

**autoConfirmUser**  
ユーザーを自動的に確認する場合は `true` に、それ以外の場合は `false` に設定します。

**autoVerifyEmail**  
`true` に設定すると、サインアップしたユーザーの E メールアドレスを検証済みとして設定します。それ以外の場合は `false` です。`autoVerifyEmail` が `true` に設定されている場合、`email` 属性は有効な null 以外の値である必要があります。それ以外の場合はエラーが発生し、ユーザーがサインアップを完了できません。  
`email` 属性がエイリアスとして選択されている場合、`autoVerifyEmail` が設定されていると、ユーザーの E メールアドレスのエイリアスが自動的に作成されます。その E メールアドレスのエイリアスが既に存在している場合は、エイリアスは新規ユーザーに移動され、以前のユーザーの E メールアドレスは未検証としてマークされます。詳細については、「[ログイン属性のカスタマイズ](user-pool-settings-attributes.md#user-pool-settings-aliases)」を参照してください。

**autoVerifyPhone**  
`true` に設定すると、サインアップしたユーザーの電話番号を検証済みとして設定します。それ以外の場合は `false` です。`autoVerifyPhone` が `true` に設定されている場合、`phone_number` 属性は有効な null 以外の値である必要があります。それ以外の場合はエラーが発生し、ユーザーがサインアップを完了できません。  
`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**] を使用して特定の E メールドメインからの新しいユーザーを自動的に確認します。このカスタムドメインに属していない新しいユーザーは、ユーザープールには追加されますが、自動的には確認されません。

------
#### [ 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` は未検証としてマークされます。E メールアドレスの場合も同様です。これを防ぐには、ユーザープール [ListUsers API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html) を使用して既存のユーザーの中に、新しいユーザーの電話番号や E メールアドレスをエイリアスとして既に使用しているユーザーがいないかどうかを確認します。

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

------

## サインアップ前の例:ユーザー名が 5 文字未満の場合にサインアップを拒否する
<a name="aws-lambda-triggers-pre-registration-example-3"></a>

次の例は、サインアップリクエストのユーザー名の長さを調べます。次の例は、ユーザーが 5 文字未満の名前を入力した場合、エラーを返します。

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

------