

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 인바운드 페더레이션 Lambda 트리거
<a name="user-pool-lambda-inbound-federation"></a>

인바운드 페더레이션 트리거는 외부 자격 증명 공급자와의 인증 프로세스 중에 페더레이션 사용자 속성을 변환합니다. 사용자가 구성된 자격 증명 공급자를 통해 인증하면이 트리거를 사용하면 인증 프로세스의 데이터를 가로채고 변환하여 외부 SAML 및 OIDC 공급자의 응답을 수정할 수 있으므로 Amazon Cognito 사용자 풀이 페더레이션 사용자 및 해당 속성을 처리하는 방법을 프로그래밍 방식으로 제어할 수 있습니다.

새 사용자를 생성하거나 기존 페더레이션 사용자 프로필을 업데이트하기 전에이 트리거를 사용하여 속성을 추가, 재정의 또는 억제합니다. 이 트리거는 원시 자격 증명 공급자 속성을 입력으로 수신하고 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>

사용자가 외부 자격 증명 공급자로 인증하면 Amazon Cognito는 사용자 프로필을 생성하거나 업데이트하기 전에 인바운드 페더레이션 트리거를 호출합니다. 트리거는 자격 증명 공급자로부터 원시 속성을 수신하고 Amazon Cognito가 저장하기 전에 변환할 수 있습니다. 이 흐름은 새 페더레이션 사용자와 페더레이션을 통해 다시 로그인하는 기존 사용자 모두에게 발생합니다.

![\[인바운드 페더레이션 Lambda 트리거 흐름\]](http://docs.aws.amazon.com/ko_kr/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**  
외부 자격 증명 공급자의 이름입니다.

**providerType**  
외부 자격 증명 공급자의 유형입니다. 유효한 값: `OIDC`, `SAML`, `Facebook`, `Google`, `SignInWithApple`, `LoginWithAmazon`.

**attributes**  
처리 전에 자격 증명 공급자로부터 받은 원시 속성입니다. 구조는 공급자 유형에 따라 다릅니다.

**attributes.tokenResponse**  
`/token` 엔드포인트의 OAuth 토큰 응답 데이터입니다. OIDC 및 소셜 공급자만 사용할 수 있습니다. `access_token`, `id_token`, `refresh_token`, `token_type`, 및 `expires_in`를 포함합니다`scope`.

**attributes.idToken**  
디코딩되고 검증된 ID 토큰 JWT 클레임. OIDC 및 소셜 공급자만 사용할 수 있습니다. `sub` (고유 사용자 식별자), `email`, `name`, `iss` (발급자), `aud` (대상), `exp` (만료), `iat` (발급된 시간) 등 확인된 사용자 자격 증명 정보를 포함합니다.

**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`자격 증명 공급자의 모든 원래 속성이 변경되지 않고 유지됩니다. 이는 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의 스토리지 제한을 초과하는 속성 값을 자르는 방법을 보여줍니다. 이 함수는 자격 증명 공급자의 각 속성을 확인합니다. 속성 값이 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"
    }
}
```

------