

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

# インバウンドフェデレーション Lambda トリガー
<a name="user-pool-lambda-inbound-federation"></a>

インバウンドフェデレーショントリガーは、外部 ID プロバイダーによる認証プロセス中にフェデレーションユーザー属性を変換します。ユーザーが設定された ID プロバイダーを介して認証する場合、このトリガーにより、認証プロセスでデータを傍受して変換することで外部 SAML プロバイダーと OIDC プロバイダーからのレスポンスを変更でき、Amazon Cognito ユーザープールがフェデレーティッドユーザーとその属性を処理する方法をプログラムで制御できます。

このトリガーを使用して、新しいユーザーを作成する前、または既存のフェデレーティッドユーザープロファイルを更新する前に、属性を追加、上書き、または抑制します。このトリガーは、raw ID プロバイダー属性を入力として受け取り、Amazon Cognito がユーザープロファイルに適用する変更された属性を返します。

**Topics**
+ [フローの概要](#cognito-user-pools-lambda-trigger-inbound-federation-flow)
+ [インバウンドフェデレーション Lambda トリガーパラメータ](#cognito-user-pools-lambda-trigger-syntax-inbound-federation)
+ [インバウンドフェデレーションの例: グループメンバーシップ管理](#aws-lambda-triggers-inbound-federation-example-groups)
+ [インバウンドフェデレーションの例: 大きな属性を切り捨てる](#aws-lambda-triggers-inbound-federation-example-truncate)
+ [インバウンドフェデレーションの例: フェデレーションイベントのログ記録](#aws-lambda-triggers-inbound-federation-example-logging)

## フローの概要
<a name="cognito-user-pools-lambda-trigger-inbound-federation-flow"></a>

ユーザーが外部 ID プロバイダーで認証されると、Amazon Cognito はユーザープロファイルを作成または更新する前にインバウンドフェデレーショントリガーを呼び出します。トリガーは ID プロバイダーから raw 属性を受け取り、Amazon Cognito が保存する前に変換できます。このフローは、フェデレーションを通じて再度サインインする新しいフェデレーティッドユーザーと既存のユーザーの両方に発生します。

![\[インバウンドフェデレーション Lambda トリガーフロー\]](http://docs.aws.amazon.com/ja_jp/cognito/latest/developerguide/images/lambda-inbound-federation.png)


## インバウンドフェデレーション Lambda トリガーパラメータ
<a name="cognito-user-pools-lambda-trigger-syntax-inbound-federation"></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 ]

```
{
    "version": "string",
    "triggerSource": "InboundFederation_ExternalProvider",
    "region": AWSRegion,
    "userPoolId": "string",
    "userName": "string",
    "callerContext": {
        "awsSdkVersion": "string",
        "clientId": "string"
    },
    "request": {
        "providerName": "string",
        "providerType": "string",
        "attributes": {
            "tokenResponse": {
                "access_token": "string",
                "token_type": "string",
                "expires_in": "string"
            },
            "idToken": {
                "sub": "string",
                "email": "string",
                "email_verified": "string"
            },
            "userInfo": {
                "email": "string",
                "given_name": "string",
                "family_name": "string"
            },
            "samlResponse": {
                "string": "string"
            }
        }
    },
    "response": {
        "userAttributesToMap": {
            "string": "string"
        }
    }
}
```

------

### インバウンドフェデレーションリクエストパラメータ
<a name="cognito-user-pools-lambda-trigger-syntax-inbound-federation-request"></a>

**providerName**  
外部 ID プロバイダーの名前。

**providerType**  
外部 ID プロバイダーのタイプ。有効な値: `OIDC`、`SAML`、、`Facebook`、`Google``SignInWithApple`、`LoginWithAmazon`。

**属性**  
処理前に ID プロバイダーから受信した raw 属性。構造はプロバイダータイプによって異なります。

**attributes.tokenResponse**  
`/token` エンドポイントからの OAuth トークンレスポンスデータ。OIDC およびソーシャルプロバイダーでのみ使用できます。`access_token`、`id_token`、、`refresh_token`、`token_type``expires_in`、および が含まれます`scope`。

**attributes.idToken**  
デコードおよび検証された ID トークン JWT クレーム。OIDC およびソーシャルプロバイダーでのみ使用できます。(一意のユーザー識別子)`email`、、`sub`、 (`iss`発行者)`name`、 `aud` (対象者）、 `exp` (有効期限）、 `iat` (発行時間) などの検証済みユーザー ID 情報が含まれます。

**attributes.userInfo**  
UserInfo エンドポイントからの拡張ユーザープロファイル情報。OIDC およびソーシャルプロバイダーでのみ使用できます。`given_name`、、`family_name`、`picture`、 などのプロバイダー固有のフィールドなど`address`、詳細なプロファイル属性が含まれます。IdP が UserInfo エンドポイントをサポートしていない場合、またはエンドポイント呼び出しが失敗した場合、空になる可能性があります。

**attributes.samlResponse**  
SAML アサーション属性。SAML プロバイダーでのみ使用できます。SAML レスポンスの属性が含まれます。

### インバウンドフェデレーションレスポンスパラメータ
<a name="cognito-user-pools-lambda-trigger-syntax-inbound-federation-response"></a>

**userAttributesToMap**  
ユーザープロファイルに適用するユーザー属性。

**重要**  
変更しない属性を含め、レスポンスに保持するすべてのユーザー属性を含める必要があります。`userAttributesToMap` レスポンスに含まれていない属性は削除され、ユーザープロファイルに保存されません。これは、変更された属性と変更されていない属性の両方に適用されます。

**空のレスポンス動作**  
に空のオブジェクトを返した場合`{}``userAttributesToMap`、ID プロバイダーからのすべての元の属性は変更されません。これは、Lambda 関数が実行されなかったかのように、no-op として機能します。これは、削除される属性を省略する場合とは異なります。

**プロバイダー固有の属性**  
の構造は、 `request.attributes`によって異なります`providerType`。OIDC およびソーシャルプロバイダーには、`tokenResponse`、`idToken`、 `userInfo` オブジェクトが含まれます。SAML プロバイダーには `samlResponse` オブジェクトのみが含まれます。

## インバウンドフェデレーションの例: グループメンバーシップ管理
<a name="aws-lambda-triggers-inbound-federation-example-groups"></a>

この例では、フェデレーティッド ID プロバイダーグループを Amazon Cognito ユーザープールグループにマッピングする方法を示します。この関数は、フェデレーティッドレスポンスからグループメンバーシップを抽出し、対応する Amazon Cognito グループにユーザーを自動的に追加するため、認証後のトリガーが不要になります。

------
#### [ Node.js ]

```
exports.handler = async (event) => {
    const { providerType, attributes } = event.request;
    
    // Extract user attributes based on provider type
    let userAttributesFromIdp = {};
    if (providerType === 'SAML') {
        userAttributesFromIdp = attributes.samlResponse || {};
    } else {
        // For OIDC and Social providers, merge userInfo and idToken
        userAttributesFromIdp = {
            ...(attributes.userInfo || {}),
            ...(attributes.idToken || {})
        };
    }
    
    // Extract groups from federated response
    const federatedGroups = userAttributesFromIdp.groups?.split(',') || [];
    
    // Map federated groups to Cognito groups
    const groupMapping = {
        'Domain Admins': 'Administrators',
        'Engineering': 'Developers',
        'Sales': 'SalesTeam'
    };
    
    // Filter to only in-scope groups
    const mappedGroups = federatedGroups
        .map(group => groupMapping[group.trim()])
        .filter(group => group); // Remove undefined values
    
    // Pass through attributes with mapped groups as custom attribute
    const attributesToMap = {
        ...userAttributesFromIdp,
        'custom:user_groups': mappedGroups.join(',')
    };
    
    // Remove original groups attribute
    delete attributesToMap.groups;
    
    event.response.userAttributesToMap = attributesToMap;
    return event;
};
```

------

Amazon Cognito は Lambda 関数にイベント情報を渡します。関数はレスポンスで、同じイベントオブジェクトを変更と共に Amazon Cognito に返します。Lambda コンソールで、Lambda トリガーに関連するデータを使用したテストイベントをセットアップできます。以下は、このコードサンプルのテストイベントです。

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

```
{
    "userPoolId": "us-east-1_XXXXXXXXX",
    "request": {
        "providerName": "CorporateAD",
        "providerType": "SAML",
        "attributes": {
            "samlResponse": {
                "email": "jane.smith@company.com",
                "given_name": "Jane",
                "family_name": "Smith",
                "groups": "Engineering,Domain Admins",
                "department": "Engineering"
            }
        }
    },
    "response": {
        "userAttributesToMap": {}
    }
}
```

------

## インバウンドフェデレーションの例: 大きな属性を切り捨てる
<a name="aws-lambda-triggers-inbound-federation-example-truncate"></a>

この例では、Amazon Cognito のストレージ制限を超える属性値を切り捨てる方法を示します。この関数は、ID プロバイダーの各属性をチェックします。属性値が 2048 文字を超える場合、値は切り捨てられ、切り捨てを示す省略記号が追加されます。他のすべての属性は変更されずに渡されます。

------
#### [ Node.js ]

```
exports.handler = async (event) => {
    const MAX_ATTRIBUTE_LENGTH = 2048;
    
    // Get the identity provider attributes based on provider type
    const { providerType, attributes } = event.request;
    let idpAttributes = {};
    
    if (providerType === 'SAML') {
        idpAttributes = attributes.samlResponse || {};
    } else {
        // For OIDC and Social providers, merge userInfo and idToken
        idpAttributes = {
            ...(attributes.userInfo || {}),
            ...(attributes.idToken || {})
        };
    }
    
    const userAttributes = {};
    
    // Process each attribute
    for (const [key, value] of Object.entries(idpAttributes)) {
        if (typeof value === 'string' && value.length > MAX_ATTRIBUTE_LENGTH) {
            // Truncate the value and add ellipsis
            userAttributes[key] = value.substring(0, MAX_ATTRIBUTE_LENGTH - 3) + '...';
            console.log(`Truncated attribute ${key} from ${value.length} to ${userAttributes[key].length} characters`);
        } else {
            // Keep the original value
            userAttributes[key] = value;
        }
    }
    
    // Return the modified attributes
    event.response.userAttributesToMap = userAttributes;
    return event;
};
```

------

Amazon Cognito は Lambda 関数にイベント情報を渡します。関数はレスポンスで、同じイベントオブジェクトを変更と共に Amazon Cognito に返します。Lambda コンソールで、Lambda トリガーに関連するデータを使用したテストイベントをセットアップできます。以下は、このコードサンプルのテストイベントです。

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

```
{
    "version": "string",
    "triggerSource": "InboundFederation_ExternalProvider",
    "region": "us-east-1",
    "userPoolId": "us-east-1_XXXXXXXXX",
    "userName": "ExampleProvider_12345",
    "callerContext": {
        "awsSdkVersion": "string",
        "clientId": "string"
    },
    "request": {
        "providerName": "ExampleProvider",
        "providerType": "OIDC",
        "attributes": {
            "tokenResponse": {
                "access_token": "abcDE...",
                "token_type": "Bearer",
                "expires_in": "3600"
            },
            "idToken": {
                "sub": "12345",
                "email": "user@example.com"
            },
            "userInfo": {
                "email": "user@example.com",
                "given_name": "Example",
                "family_name": "User",
                "bio": "This is a very long biography that contains more than 2048 characters..."
            }
        }
    },
    "response": {
        "userAttributesToMap": {}
    }
}
```

------

## インバウンドフェデレーションの例: フェデレーションイベントのログ記録
<a name="aws-lambda-triggers-inbound-federation-example-logging"></a>

この例では、モニタリングとデバッグのためにフェデレーティッド認証イベントを記録する方法を示します。このサンプル関数は、フェデレーティッドユーザーとその属性に関する詳細情報をキャプチャし、認証プロセスを可視化します。

------
#### [ Node.js ]

```
exports.handler = async (event) => {
    const { providerName, providerType, attributes } = event.request;
    
    // Extract user attributes based on provider type
    let userAttributesFromIdp = {};
    if (providerType === 'SAML') {
        userAttributesFromIdp = attributes.samlResponse || {};
    } else {
        // For OIDC and Social providers, merge userInfo and idToken
        userAttributesFromIdp = {
            ...(attributes.userInfo || {}),
            ...(attributes.idToken || {})
        };
    }
    
    // Log federated authentication details
    console.log(JSON.stringify({
        timestamp: new Date().toISOString(),
        providerName,
        providerType,
        userEmail: userAttributesFromIdp.email,
        attributeCount: Object.keys(userAttributesFromIdp).length,
        attributes: userAttributesFromIdp
    }));
    
    // Pass through all attributes unchanged
    event.response.userAttributesToMap = userAttributesFromIdp;
    return event;
};
```

------

Amazon Cognito は Lambda 関数にイベント情報を渡します。関数はレスポンスで、同じイベントオブジェクトを変更と共に Amazon Cognito に返します。Lambda コンソールで、Lambda トリガーに関連するデータを使用したテストイベントをセットアップできます。以下は、このコードサンプルのテストイベントです。

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

```
{
    "version": "string",
    "triggerSource": "InboundFederation_ExternalProvider",
    "region": "us-east-1",
    "userPoolId": "us-east-1_XXXXXXXXX",
    "userName": "CorporateAD_john.doe",
    "callerContext": {
        "awsSdkVersion": "string",
        "clientId": "string"
    },
    "request": {
        "providerName": "CorporateAD",
        "providerType": "SAML",
        "attributes": {
            "samlResponse": {
                "email": "john.doe@company.com",
                "given_name": "John",
                "family_name": "Doe",
                "department": "Engineering",
                "employee_id": "EMP12345"
            }
        }
    },
    "response": {
        "userAttributesToMap": {}
    }
}
```

------

予想される CloudWatch Logs 出力:

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

```
{
    "timestamp": "2025-01-14T21:17:40.153Z",
    "providerName": "CorporateAD",
    "providerType": "SAML",
    "userEmail": "john.doe@company.com",
    "attributeCount": 5,
    "attributes": {
        "email": "john.doe@company.com",
        "given_name": "John",
        "family_name": "Doe",
        "department": "Engineering",
        "employee_id": "EMP12345"
    }
}
```

------