Cognito details not being passed to Lambda through AppSync

  Kiến thức lập trình

I’m creating an app that utilises Lambda that is called with AppSync (both setup within aws_cdk). In the Lambda’s I need to use the logged in user (done via cognito) details within it to retrieve data per person (I don’t want to pass user data in args as don’t want it being manipulated easily).

When the lambda is triggered within the event the request_mapping_template values that are pointing to cognito are set to null, and the context returns client_context=None,identity=CognitoIdentity([cognito_identity_id=None,cognito_identity_pool_id=None])

However the appsync api is only able to be called with the user logged into cognito within the assigned userpool meaning that the cogntio data is there somewhere.

See below the function created that the Lambda’s are all using to be set up within aws_cdk (I assume this code is where my error lies)

from os import path

from aws_cdk import Duration
from aws_cdk import aws_appsync as appsync
from aws_cdk import aws_iam as iam
from aws_cdk import aws_lambda as lmb
from aws_cdk import aws_logs as logs
from constructs import Construct


class AppsyncLambdaAPI(Construct):
    """Construct to create a GraphQL API consiting of a lambda function as the data source.
    :param construct_id -- The name of the specific instance of this construct
    :param env_id -- The environment ID
    :param appsync_api -- The AppSync API chosen for integration
    :param api_type -- The type of API request - Options: Query or Mutation
    :param graphql_field -- The exact name of the query or mutation defined in the schema
    :param code_dir_name -- The name of the directory containing the Lambda API code
    :param lambda_api_policy -- OPTIONAL - The policy containing any permissions required for the lambda, Type: iam.ManagedPolicy # noqa: E501
    :param dynamodb_table -- OPTIONAL - The DynamoDB table required for data access, Type: dynamodb.Table # noqa: E501
    :param dynamodb_access -- OPTIONAL - The access type required for the DynamoDB table, Type: str - Options: READ, READ_WRITE # noqa: E501
    :param lambda_log_retention -- OPTIONAL - Lambda log retention, must be one of the values from aws_cdk logs.RetentionDays # noqa: E501
    """

    def __init__(
        self,
        scope: Construct,
        construct_id: str,
        env_id: str,
        appsync_api: appsync.GraphqlApi,
        environment_variables: dict,
        api_type: str,
        graphql_field: str,
        code_dir_name: str,
        lambda_api_policy=None,
        lambda_log_retention=logs.RetentionDays.SIX_MONTHS,
        dynamodb_table=None,
        dynamodb_access=None,
        **kwargs,
    ) -> None:
        super().__init__(scope, construct_id, **kwargs)

        this_dir = path.dirname(__file__)

        # Import Lambda execution policy
        lambda_exec_policy = iam.ManagedPolicy.from_managed_policy_arn(
            self,
            id="lambda-exec-policy",
            managed_policy_arn="arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
        )

        api_lambda_role = iam.Role(
            self,
            f"{construct_id}-lambda-role",
            description=f"Role used by {construct_id} lambda function",
            assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"),
        )

        api_lambda_role.add_managed_policy(lambda_exec_policy)

        # Attach policy to lambda role if passed in to the construct
        if lambda_api_policy is not None:
            api_lambda_role.add_managed_policy(lambda_api_policy)

        # Load powertools layer arn
        powertools_layer_arn = self.node.try_get_context(env_id)[
            "powertools_lambda_layer_arn"
        ]

        # Define Lambda Powertools layer
        powertools_layer = lmb.LayerVersion.from_layer_version_arn(
            self, "LambdaPowertoolsLayer", layer_version_arn=powertools_layer_arn
        )

        # Define lambda API handler
        environment_variables["LOG_LEVEL"] = self.node.try_get_context(env_id)[
            "log_level"
        ]
        
        api_lambda_handler = lmb.Function(
            self,
            f"{construct_id}-Lambda",
            description=f"Lambda function which handles requests for the {construct_id}",
            function_name=f"{code_dir_name}_handler_{env_id}",
            handler=f"{code_dir_name}.handler",
            runtime=lmb.Runtime.PYTHON_3_9,
            code=lmb.Code.from_asset(
                path.join(this_dir, f"../../functions/{code_dir_name}")
            ),
            tracing=lmb.Tracing.ACTIVE,
            timeout=Duration.seconds(20),
            role=api_lambda_role,
            environment=environment_variables,
            layers=[powertools_layer],
            log_retention=lambda_log_retention,
        )

        # Grant the api lambda the necessary permission to access the DynamoDB table
        if dynamodb_access == "READ":
            dynamodb_table.grant_read_data(api_lambda_handler)
        elif dynamodb_access == "READ_WRITE":
            dynamodb_table.grant_read_write_data(api_lambda_handler)
        else:
            pass

        # Add lambda as data source to AppSync
        api_lambda_ds = appsync_api.add_lambda_data_source(
            f"{code_dir_name}_lambda_ds_{env_id}", api_lambda_handler
        )

        # Define lambda resolvers according to schema defintion
        api_lambda_ds.create_resolver(
            id=f"{construct_id}-resolver",
            type_name=api_type,
            field_name=graphql_field,
            request_mapping_template=appsync.MappingTemplate.from_string(
                f"""
            {{
                "version": "2017-02-28",
                "operation": "Invoke",
                "payload": {{
                    "field":"{graphql_field}",
                    "student_code": 
                        $util.toJson($context.authorizer.claims.get("custom:student_code")),
                    "usertype":$util.toJson($context.authorizer.claims.get("custom:user_type")),
                    "username": $util.toJson($context.authorizer.claims.get("custom:username")),
                    "email":$util.toJson($context.authorizer.claims.identities[0].get("email")),
                    "arguments": $util.toJson($context.arguments)
                }}
            }}
            """
            ),
            response_mapping_template=appsync.MappingTemplate.from_string(
                """
            #if( $context.result && $context.result.error )
                $util.error($ctx.result.error.message, $ctx.result.error.type)
            #else
                $util.toJson($context.result)
            #end
            """
            ),
        )

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT