简体   繁体   中英

How to retrieve cognito identification data in Appsync Lambda Resolver (Using cdk)

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM