Lesson 4 of 7 Amazon API Gateway

Controlling Access to APIs with Authorizers, Resource Policies and CORS

This lesson explains how API Gateway authenticates callers, decides what they may invoke, restricts where requests come from and blocks malicious traffic before any of it reaches the backend.

Learning outcomes

After completing this lesson, you will be able to:

  • Choose between IAM authorization, Amazon Cognito user pool authorizers, JWT authorizers and Lambda authorizers.
  • Distinguish TOKEN and REQUEST Lambda authorizers and explain how their results are cached.
  • Describe how resource policies and AWS WAF restrict callers and filter malicious requests.
  • Explain how cross-origin resource sharing (CORS) works and why a browser blocks a request that lacks it.

Authorization options

API Gateway can authenticate callers before a request reaches the backend, so the backend does not need to verify credentials itself. The right option depends on how callers prove their identity.

IAM authorization requires callers to sign each request with Signature Version 4 using AWS credentials, and allows the call only if the caller's IAM policy grants execute-api:Invoke on the method. It suits other AWS services, internal applications and users who obtain credentials from a Cognito identity pool. A Cognito user pool authorizer checks the token that a user received when signing in to a Cognito user pool, verifying its signature and expiry with no custom code; it is available for REST APIs. For HTTP APIs, a JWT authorizer performs the same validation for tokens from Cognito or any OpenID Connect or OAuth 2.0 provider, and can require specific scopes.

A Lambda authorizer runs your own function, which receives the token or the request parameters, decides whether to allow the call and returns an IAM policy. It handles token formats that the built-in options cannot, such as a third-party token or a check against a database. API Gateway caches the result for a configurable time, 300 seconds by default, so the function does not run on every request.

The following table summarises the options.

OptionHow it worksBest for
IAMCallers sign requests with Signature Version 4Callers that already have AWS credentials
Cognito user pool authorizerValidates tokens issued by a Cognito user pool, with no codeApps that sign users in with Cognito
JWT authorizer (HTTP APIs)Validates JWTs from any OIDC or OAuth 2.0 providerHTTP APIs with standard tokens
Lambda authorizerYour function checks the request and returns an IAM policyThird-party or custom token formats

Lambda authorizers

There are two kinds of Lambda authorizer:

  • TOKEN: receives a bearer token from one header.
  • REQUEST: receives headers, query strings, stage variables and context, so it can decide using several values.

Results can be cached for up to one hour, keyed by the token or identity sources. A cached Allow or Deny applies until it expires.

Example. This TOKEN authorizer validates a JWT and returns a policy. Because a cached policy is reused for other methods, it allows a wildcard resource. The context values reach the backend as $context.authorizer.tenantId.

def handler(event, context):
    claims = verify_jwt(event["authorizationToken"])        # raise to return 401 Unauthorized
    api_arn = event["methodArn"].split("/")[0]               # arn:aws:execute-api:region:acct:api-id
    return {
        "principalId": claims["sub"],
        "policyDocument": {
            "Version": "2012-10-17",
            "Statement": [{"Action": "execute-api:Invoke", "Effect": "Allow", "Resource": f"{api_arn}/*"}],
        },
        "context": {"tenantId": claims["tenant"]},
    }

Resource policies and AWS WAF

API Gateway can restrict callers and filter malicious requests before they reach the backend. The following list describes the relevant features.

  • Resource policies on REST APIs allow or deny callers by AWS account, IP range or VPC endpoint, for example to restrict an API to corporate IP addresses.
  • AWS WAF attaches to REST API stages to block common exploits such as SQL injection and to rate-limit individual IP addresses.

CORS

When a browser calls the API from a different origin, the API must support CORS: it answers the OPTIONS preflight request and returns Access-Control-Allow-* headers. With a Lambda proxy integration, the function must also return these headers itself, and gateway responses must add them to errors that API Gateway generates, such as a rejected token.

Worked example

A browser app blocked by CORS

A single-page app at https://app.example.com calls an API at https://api.example.com with a Cognito token. The browser blocks the call with a CORS error, although the same request works from curl.

CheckFinding
PreflightThe browser sends OPTIONS first because of the Authorization header; the API had no OPTIONS method
Response headersThe Lambda proxy response lacked Access-Control-Allow-Origin
Error responsesWhen the authorizer rejects a token, API Gateway's own 401 response also lacked CORS headers

The developer enables CORS on the resource (adding the OPTIONS method), returns the CORS headers from the Lambda function, and adds them to the gateway responses for 4XX and 5XX errors. Curl worked all along because CORS is enforced only by browsers.

Check yourself

A web app sends a Cognito user pool token to a REST API. Which authorizer validates the token with no custom code?

Show answer

A Cognito user pool authorizer. It checks the token's signature and expiry itself; a Lambda authorizer is needed only for other token types or custom logic.

Exam Tips

Remember for the exam

  • Tokens from a third-party identity provider that need custom validation call for a Lambda authorizer.
  • Decisions based on several headers or query strings need a REQUEST-type Lambda authorizer.
  • Users signed in through Cognito are authorised with no code by a Cognito user pool authorizer.
  • To restrict an API to particular IP ranges, accounts or VPC endpoints, use a resource policy.
  • A browser error about Access-Control-Allow-Origin means CORS must be enabled.