1

I have an appsync lambda resolver which will query a postgresql database. Appsync requests are authorized using API keys for unauthorized users and cognito user pools for authorized users. I would like to retrieve identification data from cognito within my lambda resolver when an authenticated user makes a request, but I can't figure out how to do so. To begin, here is my setup for appsync and the lambda resolver:

    this.api = new appsync.GraphqlApi(this, "API-NAME", {
      name: "API-NAME",
      schema: appsync.Schema.fromAsset("graphql/schema.graphql"),
      authorizationConfig: {
        defaultAuthorization: {
          authorizationType: appsync.AuthorizationType.API_KEY,
          apiKeyConfig: {
            expires: cdk.Expiration.after(cdk.Duration.days(365)),
          },
        },
        additionalAuthorizationModes: [
          {
            authorizationType: appsync.AuthorizationType.USER_POOL,
            userPoolConfig: {
              userPool: props.userPool,
            },
          },
        ],
      },
    });

const lambdaDs = this.api.addLambdaDataSource(
      "lambdaDatasource",
      props.LambdaConnectingGraphqlToDatabase
    );


lambdaDs.createResolver({
      typeName: "Query",
      fieldName: "listUsers",
    });

// etc. etc.

Within my lambda resolver, context.identity is undefined even when an authenticated user makes a request. I have tried using a request mapping template within the lambdaDs.createResolver(), but I couldn't figure out how to make this work, or if this is the correct method.

How do I see the authentication data within my lambda resolver? Thank you.

Andrew Pulver
  • 178
  • 12

1 Answers1

1

You can provide the identity information to your lambda via the resolver mapping template, see https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference.html

The context.identity section is the relevant one.

There is a section with fields available for the AMAZON_COGNITO_USER_POOLS authorization.

However, note that for API_KEY, context.identity information is not populated.

You can however differentiate between the two scenarios since you will have identity information for Cognito scenario in your lambda, and will not have any identity information for API key scenario (hence you can assume it is request from unauthorized user with API key).

Milan Gatyás
  • 2,509
  • 1
  • 17
  • 23
  • 1
    Thank you for this. I was doing this but I couldn't figure out why it wasn't working. But I realized I needed to put the aws cognito directive in my schema.graphql. Before, I had been using api_key authorization without even knowing it. So, to others out there: use authMode="AMAZON_COGNITO_USER_POOLS" on client side (if using amplify client libraries) and on serverside, be sure to add @aws_cognito_user_pools to queries/mutations AND the data types. – Andrew Pulver Oct 14 '21 at 18:34