Skip to main content

AWS DVA-C02 Drill: API Gateway Authentication - Native Cognito Authorizer vs. Lambda Custom Logic

Jeff Taakey
Author
Jeff Taakey
21+ Year Enterprise Architect | AWS SAA/SAP & Multi-Cloud Expert.

Jeff’s Note
#

Jeff’s Note
#

“Unlike generic exam dumps, ADH analyzes this scenario through the lens of a Real-World Lead Developer.”

“For DVA-C02 candidates, the confusion often lies in over-engineering authentication when AWS provides native integrations. In production, this is about knowing exactly which API Gateway authorizer type minimizes custom code and leverages managed services. Let’s drill down.”


The Certification Drill (Simulated Question)
#

Scenario
#

TechFlow Solutions has deployed a customer feedback application that uses Amazon Cognito user pools to manage user identities and authentication. The development team is now tasked with exposing a new REST API through API Gateway that must validate incoming requests using the existing Cognito user pool. The lead developer wants to implement this authentication layer with minimal custom code and maintenance overhead while ensuring secure token validation.

The Requirement:
#

Implement API Gateway authentication that validates requests against the existing Amazon Cognito user pool with the least amount of development effort.

The Options
#

  • A) Create a new API key and a new usage plan. Associate the API key and the REST API with the usage plan.
  • B) Create a Cognito authorizer for the correct user pool. Reference the header that contains the Cognito token.
  • C) Create an AWS Lambda token authorizer. Reference the authorization token in the event payload. Authenticate requests based on the token value.
  • D) Create an AWS Lambda request authorizer. Reference the authorization header in the event payload. Authenticate requests by using the header value in a request to the Cognito API.


Correct Answer
#

Option B.

Quick Insight: The Native Integration Imperative
#

For Developers: API Gateway provides native Cognito authorizer functionality that automatically validates JWT tokens without custom Lambda code. This leverages AWS-managed token validation logic, reducing code complexity and eliminating the need to implement JWT parsing, signature verification, and token expiration checks manually.


Content Locked: The Expert Analysis
#

You’ve identified the answer. But do you know the implementation details that separate a Junior from a Senior?


The Expert’s Analysis
#

Correct Answer
#

Option B: Create a Cognito authorizer for the correct user pool. Reference the header that contains the Cognito token.

The Winning Logic
#

This solution is correct because it leverages API Gateway’s native Cognito user pool authorizer, which provides:

  • Zero Custom Code: The authorizer automatically validates JWT tokens issued by Cognito without requiring Lambda functions.
  • Automatic Token Validation: API Gateway performs signature verification, token expiration checks, and audience validation automatically.
  • Standard OAuth 2.0 Flow: Uses the Authorization header with Bearer token format (Authorization: Bearer <JWT_TOKEN>).
  • Built-in Caching: Token validation results can be cached (configurable TTL), reducing latency and Cognito API calls.
  • Direct Integration: Configured directly in the API Gateway console or via SDK/CloudFormation without additional infrastructure.

Developer Implementation Details:

# AWS CLI command to create a Cognito authorizer
aws apigateway create-authorizer \
  --rest-api-id abc123 \
  --name MyCognitoAuthorizer \
  --type COGNITO_USER_POOLS \
  --provider-arns arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_AbCdEfGhI \
  --identity-source 'method.request.header.Authorization'

Key Configuration Parameters:

  • --type COGNITO_USER_POOLS: Specifies native Cognito integration
  • --provider-arns: ARN of the Cognito user pool
  • --identity-source: HTTP header containing the JWT token (typically Authorization)

The Trap (Distractor Analysis):
#

  • Why not Option A (API Keys with Usage Plans)?

    • API keys are for usage throttling and quota management, not authentication
    • They don’t validate user identity or integrate with Cognito
    • API keys are shared credentials, not user-specific tokens
    • This is a fundamentally different use case (rate limiting vs. identity validation)
  • Why not Option C (Lambda Token Authorizer)?

    • Technically functional but requires writing custom Lambda code
    • You must manually implement JWT token parsing (libraries like jsonwebtoken)
    • Requires fetching and caching Cognito public keys (JWKS endpoint)
    • Adds operational overhead: Lambda cold starts, error handling, logging
    • Violates the “LEAST development effort” requirement
    • Use case: Only when you need custom authorization logic beyond Cognito (e.g., database lookups, external OAuth providers)
  • Why not Option D (Lambda Request Authorizer)?

    • Similar to Option C but with additional complexity
    • Request authorizers receive the entire request context (headers, query strings, path)
    • Still requires manual Cognito API calls to validate tokens
    • Higher latency compared to native Cognito authorizer
    • Use case: When authorization depends on request parameters beyond the token (e.g., resource-based permissions)

The Technical Blueprint
#

Authentication Flow with Native Cognito Authorizer:

// Client-side: Obtaining and using the Cognito JWT token
const AWS = require('aws-sdk');
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();

// Step 1: User authenticates with Cognito
const authParams = {
  AuthFlow: 'USER_PASSWORD_AUTH',
  ClientId: 'your-app-client-id',
  AuthParameters: {
    USERNAME: '[email protected]',
    PASSWORD: 'UserPassword123!'
  }
};

cognitoidentityserviceprovider.initiateAuth(authParams, (err, data) => {
  if (err) console.error(err);
  else {
    const idToken = data.AuthenticationResult.IdToken;
    
    // Step 2: Call API Gateway with the token
    fetch('https://your-api-id.execute-api.us-east-1.amazonaws.com/prod/resource', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${idToken}`,
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => console.log(data));
  }
});

Backend Configuration (CloudFormation Snippet):

CognitoAuthorizer:
  Type: AWS::ApiGateway::Authorizer
  Properties:
    Name: MyCognitoAuthorizer
    Type: COGNITO_USER_POOLS
    IdentitySource: method.request.header.Authorization
    RestApiId: !Ref MyRestApi
    ProviderARNs:
      - !GetAtt MyCognitoUserPool.Arn

ApiGatewayMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    AuthorizationType: COGNITO_USER_POOLS
    AuthorizerId: !Ref CognitoAuthorizer
    HttpMethod: GET
    ResourceId: !Ref MyResource
    RestApiId: !Ref MyRestApi

The Comparative Analysis
#

Option API Complexity Development Effort Performance Best Use Case
A) API Keys + Usage Plans Low Low High (no token validation) Rate limiting/throttling, not authentication
B) Native Cognito Authorizer Low Minimal (Config-only) High (Built-in caching) Standard Cognito-based authentication
C) Lambda Token Authorizer High High (Custom code) Medium (Cold starts) Custom OAuth providers, complex token logic
D) Lambda Request Authorizer Very High Very High (Full request parsing) Medium-Low (Larger payload) Fine-grained authorization based on request context

Key Decision Matrix for DVA-C02:

  • Use Native Cognito Authorizer (B) when: You have Cognito user pools and need JWT validation
  • Use Lambda Token Authorizer (C) when: Third-party OAuth providers or custom claims validation
  • Use Lambda Request Authorizer (D) when: Authorization depends on request parameters (e.g., resource-based policies)
  • Use API Keys (A) when: You need usage throttling, NOT authentication

Real-World Application (Developer Insight)
#

Exam Rule
#

“For the DVA-C02 exam, when you see ‘Amazon Cognito user pool’ + ‘LEAST development effort’, always choose the native Cognito authorizer over Lambda-based custom solutions.”

Real World
#

“In production, we use native Cognito authorizers for 90% of authentication scenarios. However, we implement Lambda token authorizers when:

  • Integrating with enterprise SSO providers (Okta, Auth0) that issue custom JWT formats
  • Performing additional authorization checks (e.g., querying DynamoDB for user permissions)
  • Implementing multi-tenancy with custom tenant isolation logic

Pro Tip: Enable authorizer result caching (TTL: 300-3600 seconds) to reduce Cognito API calls and improve latency. Monitor 4XX errors in CloudWatch to detect authorization failures.”

Debugging Tip for Developers:

# Enable CloudWatch logging for API Gateway to troubleshoot authorization failures
aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:us-east-1:123456789012:log-group:api-gateway-logs

# Common 401 Unauthorized causes:
# 1. Token expired (check exp claim in JWT)
# 2. Wrong Cognito user pool ARN in authorizer
# 3. Missing 'Authorization' header in request
# 4. Token audience (aud) doesn't match App Client ID

Stop Guessing, Start Mastering
#


Disclaimer

This is a study note based on simulated scenarios for the AWS DVA-C02 exam. Always refer to the official AWS documentation and hands-on practice for the most current implementation details.

The DevPro Network: Mission and Founder

A 21-Year Tech Leadership Journey

Jeff Taakey has driven complex systems for over two decades, serving in pivotal roles as an Architect, Technical Director, and startup Co-founder/CTO.

He holds both an MBA degree and a Computer Science Master's degree from an English-speaking university in Hong Kong. His expertise is further backed by multiple international certifications including TOGAF, PMP, ITIL, and AWS SAA.

His experience spans diverse sectors and includes leading large, multidisciplinary teams (up to 86 people). He has also served as a Development Team Lead while cooperating with global teams spanning North America, Europe, and Asia-Pacific. He has spearheaded the design of an industry cloud platform. This work was often conducted within global Fortune 500 environments like IBM, Citi and Panasonic.

Following a recent Master’s degree from an English-speaking university in Hong Kong, he launched this platform to share advanced, practical technical knowledge with the global developer community.


About This Site: AWS.CertDevPro.com


AWS.CertDevPro.com focuses exclusively on mastering the Amazon Web Services ecosystem. We transform raw practice questions into strategic Decision Matrices. Led by Jeff Taakey (MBA & 21-year veteran of IBM/Citi), we provide the exclusive SAA and SAP Master Packs designed to move your cloud expertise from certification-ready to project-ready.