Authentication overview

AWS API Gateway provides multiple mechanisms to secure API endpoints, allowing developers to control who can access their APIs and what actions they can perform. These mechanisms integrate with other AWS services, enabling granular permissions and robust security models for various applications, from public-facing APIs to internal microservices. The choice of authentication method depends on the API's consumers, the required level of granularity, and existing identity providers.

Authentication in AWS API Gateway operates at different levels: API, resource, and method. This allows for flexible security configurations, where some API methods might require strong authentication (e.g., for sensitive data), while others might be publicly accessible (e.g., for unauthenticated reads). Implementing the correct authentication strategy is crucial for protecting backend resources and ensuring data integrity and confidentiality.

Supported authentication methods

AWS API Gateway supports several distinct authentication methods, each suitable for different scenarios and security requirements. Understanding these options helps in designing an API with appropriate access controls.

  • AWS Identity and Access Management (IAM): This method uses AWS IAM users, roles, and policies to control access to API Gateway endpoints. It's ideal for securing APIs accessed by other AWS services, EC2 instances, or applications running within the AWS ecosystem. IAM policies define precise permissions, specifying which API methods a principal can invoke (defining IAM permissions for API Gateway).
  • Amazon Cognito User Pools: Cognito User Pools provide a managed user directory service that can be integrated directly with API Gateway. This is particularly useful for web and mobile applications that require user sign-up, sign-in, and token-based authentication (JWTs). API Gateway validates the JWTs issued by Cognito User Pools to authorize requests (integrating API Gateway with Amazon Cognito).
  • Lambda Authorizers (formerly Custom Authorizers): These are custom Lambda functions that you write to control access to your API methods. A Lambda authorizer receives an incoming request's identity source (e.g., a bearer token, a header value) and returns an IAM policy. This method offers the most flexibility, allowing integration with third-party identity providers or custom authentication logic (e.g., OAuth 2.0, SAML, or bespoke token validation) (understanding Lambda authorizers). For example, a Lambda authorizer could validate OAuth 2.0 access tokens from a provider like Google (Google OAuth 2.0 documentation).
  • API Keys: API keys are simple alphanumeric strings that clients include in their requests to identify themselves. While they do not provide strong authentication (they identify the calling application, not the user), they are useful for basic usage tracking, throttling, and monetizing API access. API keys can be associated with usage plans to enforce rate limits and quotas (using API keys with API Gateway).
AWS API Gateway Authentication Methods Comparison
Method When to Use Security Level
AWS IAM Internal services, AWS-native applications, machine-to-machine authentication. High (cryptographically signed requests, granular policies).
Amazon Cognito User Pools Web and mobile applications with human users, managed user directories. High (JWT-based, integrated user management).
Lambda Authorizers Custom authentication logic, integrating with external identity providers (e.g., OAuth 2.0, SAML), multi-factor authentication. Variable (depends on custom logic, can be very high).
API Keys Usage metering, throttling, identifying client applications, not for user authentication. Low (basic identification, not strong authentication).

Getting your credentials

The process for obtaining and managing credentials varies based on the chosen authentication method:

  • For AWS IAM:
    • Access Keys: For programmatic access, create an IAM user or role and generate access keys (an access key ID and a secret access key) in the AWS Management Console (creating an IAM user). These keys are used to cryptographically sign requests according to the AWS Signature Version 4 (SigV4) process.
    • IAM Roles: For applications running on AWS services (e.g., Lambda functions, EC2 instances), assign an IAM role. The application can then assume this role and obtain temporary credentials, avoiding the need to manage long-lived access keys (IAM roles overview).
  • For Amazon Cognito User Pools:
    • User Sign-up/Sign-in: Users authenticate directly with your Cognito User Pool, typically through a web UI or mobile SDK. Upon successful authentication, Cognito issues JSON Web Tokens (JWTs) – an ID token, an access token, and a refresh token (getting started with Cognito User Pools).
    • Client Applications: You configure app clients within your Cognito User Pool, which represent the applications (web, mobile) that will interact with the User Pool. These app clients have IDs that are used by your application to initiate the authentication flow.
  • For Lambda Authorizers:
    • Custom Logic: The credentials depend entirely on your custom Lambda authorizer's implementation. This could be an API key, an OAuth token, a custom JWT, or any other identifier your authorizer is designed to validate.
    • Deployment: The Lambda function itself is deployed and managed like any other AWS Lambda function, with appropriate IAM permissions to execute and potentially interact with other services for token validation or user lookup.
  • For API Keys:
    • Generation: API keys are generated within the API Gateway console or via the AWS CLI/SDKs (creating API keys in API Gateway).
    • Association: After creation, API keys are associated with one or more usage plans, which in turn are linked to specific API stages. Clients receive these keys and include them in the x-api-key header of their requests.

Authenticated request example

Below are examples of how to make authenticated requests to an AWS API Gateway endpoint using different methods. For simplicity, these examples assume a basic setup.

Example: Request with AWS IAM (SigV4)

For IAM-authenticated APIs, requests must be cryptographically signed using AWS Signature Version 4. This typically involves using an AWS SDK, which handles the complex signing process automatically. Here's a Python (Boto3) example:


import boto3
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest

# Replace with your API Gateway endpoint, region, and service
api_gateway_endpoint = "https://your-api-id.execute-api.your-region.amazonaws.com/your-stage/your-resource"
aws_region = "your-region"
aws_service = "execute-api"

# Using a default session will pick up credentials from environment variables, ~/.aws/credentials, etc.
session = boto3.Session()
credentials = session.get_credentials()

# Create a request object
request = AWSRequest(method="GET", url=api_gateway_endpoint, data=None)

# Sign the request
SigV4Auth(credentials, aws_service, aws_region).add_auth(request)

# Prepare the signed request for the requests library
prepared_request = request.prepare()

# Send the request
response = requests.request(
    method=prepared_request.method,
    url=prepared_request.url,
    headers=prepared_request.headers,
    data=prepared_request.body
)

print(f"Status Code: {response.status_code}")
print(f"Response Body: {response.text}")

Example: Request with Amazon Cognito User Pool (JWT)

After a user authenticates with Cognito, your client application will receive a JWT. This token is then included in the Authorization header of requests to API Gateway.


// Assuming 'idToken' is obtained after successful Cognito authentication
const idToken = "YOUR_COGNITO_ID_TOKEN"; 
const apiEndpoint = "https://your-api-id.execute-api.your-region.amazonaws.com/your-stage/your-resource";

fetch(apiEndpoint, {
  method: 'GET',
  headers: {
    'Authorization': idToken,
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Example: Request with API Key

API keys are typically passed in the x-api-key header.


curl -X GET \
  https://your-api-id.execute-api.your-region.amazonaws.com/your-stage/your-resource \
  -H 'x-api-key: YOUR_API_KEY'

Security best practices

Implementing authentication is only one part of securing your APIs. Adhering to best practices enhances the overall security posture:

  • Least Privilege: Grant only the necessary permissions to IAM users, roles, and authenticated users. For IAM, use fine-grained policies that restrict access to specific API methods and resources (IAM best practices for least privilege). For Cognito, use identity pools to map authenticated users to IAM roles with limited permissions.
  • Manage API Keys Securely: API keys should be treated as sensitive credentials. Do not hardcode them in client-side code, commit them to version control, or embed them directly in publicly accessible files. Consider environment variables, secret management services (like AWS Secrets Manager), or secure configuration files. Rotate API keys regularly.
  • Use Lambda Authorizers for Custom Logic: If your authentication requirements go beyond what IAM or Cognito User Pools offer, leverage Lambda authorizers. This allows you to integrate with enterprise identity providers, implement multi-factor authentication, or enforce complex authorization rules based on custom attributes.
  • Enable Request Validation: Configure API Gateway request validators to ensure incoming requests conform to defined schemas. This helps prevent common attacks like injection by rejecting malformed requests before they reach your backend (API Gateway request validation).
  • Implement Throttling and Usage Plans: Protect your backend services from abuse and denial-of-service (DoS) attacks by configuring throttling limits and usage plans. This controls the rate at which clients can invoke your API methods, even for authenticated requests.
  • Monitor and Log Access: Enable AWS CloudTrail for API Gateway to log all API calls, including who made the call, from where, and when. Use Amazon CloudWatch Logs to monitor Lambda authorizer execution logs and API Gateway access logs for suspicious activity.
  • Regular Security Audits: Periodically review your API Gateway configurations, authentication methods, IAM policies, and Lambda authorizer code. Ensure that all access controls remain appropriate for your current security requirements and threat landscape.
  • Keep Dependencies Updated: Ensure that any libraries, frameworks, or SDKs used in your Lambda authorizers or client applications are kept up-to-date to patch known vulnerabilities.