How to Securely Deploy APIs to Amazon Lambda: Complete Tutorial
By Braincuber Team
Published on March 5, 2026
Cyber attacks against APIs are on the increase. Authentication failures, authorization bypasses, unnecessary data exposure, lack of request limits, unchecked resource consumption — these aren't hypothetical risks. They're the OWASP Top 10 for API security, and most serverless deployments skip at least 3 of them. Deploying an API to Lambda without security is like putting a toll booth on a highway with no barriers — anyone drives through. This complete tutorial walks you through deploying APIs to AWS Lambda with every security layer a production deployment needs: Cognito for authentication, API Gateway for authorization, WAF for firewall inspection, and Secrets Manager for secure credential storage.
What You'll Learn:
- How to set up AWS environment with secure IAM access keys
- How to configure SNS topics and store ARNs in Secrets Manager
- How to create Internal and External Lambda functions
- How to configure Web Application Firewall (WAF) with IP filtering
- How to set up Cognito User Pools with authentication flows
- How to configure API Gateway with Cognito Authorizers
- How to test the complete end-to-end secure API flow
The Architecture: 5 Security Layers Deep
When a user sends a request to an API hosted in Lambda, the request passes through 5 security checkpoints before reaching the actual API code. First, Cognito authenticates the user. The request then passes through WAF for firewall inspection. API Gateway checks the authorization token. Only then does traffic reach the External Lambda function, which retrieves credentials from Secrets Manager to communicate with SNS and the Internal Lambda. Each layer protects against a different attack vector.
Amazon Cognito
Identity management that handles user creation, authentication, and token generation. Each user pool provides sign-up/sign-in flows and issues JWT tokens that API Gateway validates before allowing access to Lambda functions.
Web Application Firewall
Inspects traffic before it reaches your APIs. Configure IP allow/deny lists, rate limiting (default 10,000, should be reduced to 50 for most APIs), and Web ACL rules. Protects against abuse, DDoS attempts, and unauthorized access patterns.
API Gateway
Serves as a reverse proxy, managing access and routing traffic to Lambda backends. Authorizers validate Cognito tokens. Resources define URL paths. Methods define POST/GET endpoints with per-resource authorization rules.
Secrets Manager
Stores sensitive data (SNS Topic ARNs, API keys, credentials) securely. Lambda functions fetch secrets at runtime instead of hardcoding them as environment variables — a critical security practice that prevents credential leaks in code repositories.
Step by Step: Building the Secure API
Set Up AWS Environment and Clone Project
Create an IAM user with administrator access (don't use root). Generate Access Key ID and Secret Access Key — download the CSV and store securely. Run aws configure to set your credentials and default region. Clone the project repository. Security best practice: never use root credentials for CLI access. The admin IAM user should have just enough permissions for the deployment.
Configure SNS and Secrets Manager
Create an SNS topic for asynchronous communication between Lambda functions. Copy the topic's ARN. Then create a secret in Secrets Manager with key TOPIC_ARN and the actual ARN as the value. This demonstrates secure credential access — your Lambda fetches the ARN at runtime from Secrets Manager instead of storing it as an environment variable. More secure, auditable, and rotatable.
Create Internal and External Lambda Functions
Create InternalLambda with the SNS topic as its trigger — it reads messages published to SNS and logs output to CloudWatch. Create two ExternalLambda functions that host the APIs. Let Lambda create default IAM roles with CloudWatch permissions. Modify External Lambda IAM roles to add GetSecretValue permission for Secrets Manager — scoped to the specific secret's ARN. Deploy the function code from your cloned repository.
Configure Web Application Firewall (WAF)
Navigate to WAF and create an IP set with allowed addresses (use CIDR notation: X.X.X.X/32 for single IPs). Create a Web ACL with Regional resources, add an IP set rule, and set the action to Count (or Block for production). This firewall inspects requests before they reach your API — filtering by IP, rate limiting, and blocking suspicious patterns. Attach the WAF to your API Gateway stage after deployment.
Set Up Cognito User Pools
Create two User Pools (one per Lambda API). Select Single-page application (SPA), set email as the sign-in attribute, and configure App clients. Edit Authentication flows to enable Sign in with username and password and Sign in with server-side administrative credentials — this lets you authenticate programmatically and fetch JWT tokens. Add a user to each pool with a valid email. Confirm accounts through the email verification flow.
Configure API Gateway with Authorizers
Create a REST API in API Gateway. Set up two Cognito Authorizers, each linked to one User Pool, using "Authorization" as the token source. Create resources (/lambda1, /lambda2) and POST methods pointing to the respective External Lambda ARNs. Attach the matching Cognito Authorizer to each method. Deploy to a stage, attach the WAF, and reduce the default rate limit from 10,000 to 50. The deploy generates an invoke URL that serves as the API base URL.
Test the End-to-End Secure Flow
Authenticate a user via Cognito to get a JWT token. Send a POST request with the token in the Authorization header. The request flows through WAF → API Gateway (validates token via Cognito Authorizer) → External Lambda → fetches SNS ARN from Secrets Manager → publishes to SNS → triggers Internal Lambda → logs to CloudWatch. Test with valid and invalid tokens to confirm unauthorized requests are rejected. Verify CloudWatch logs show the expected output.
SECURE LAMBDA API DEPLOYMENT CHECKLIST
Layer 1: Authentication
[ ] Cognito User Pools created
[ ] App clients configured (programmatic auth)
[ ] Users added and email-verified
[ ] JWT token generation tested
Layer 2: Firewall
[ ] WAF IP sets configured (CIDR notation)
[ ] Web ACL created with IP rules
[ ] Rate limit reduced from 10,000 to 50
[ ] WAF attached to API Gateway stage
Layer 3: Authorization
[ ] API Gateway Cognito Authorizers created
[ ] Token source set to "Authorization" header
[ ] Per-resource Authorizer assignment
[ ] Unauthorized requests return 401
Layer 4: Secrets Management
[ ] SNS Topic ARN stored in Secrets Manager
[ ] Lambda IAM role has GetSecretValue permission
[ ] Permission scoped to specific secret ARN
[ ] No credentials in environment variables
Layer 5: Lambda Security
[ ] Minimal IAM permissions (least privilege)
[ ] CloudWatch logging enabled
[ ] No console.log in production code
[ ] All resources in same AWS region
Don't Skip the Rate Limit
The default API Gateway rate limit is 10,000 requests per second. For most APIs, that's insanely high and opens the door to cost-based DDoS attacks — an attacker doesn't need to take your API down, just rack up a $47,000 Lambda bill overnight. Reduce the rate limit to match your actual traffic patterns. 50 requests/second is sensible for most ecommerce APIs. You can always increase it as traffic grows.
Frequently Asked Questions
What security services does this tutorial use?
Five AWS services: Amazon Cognito for user authentication, Web Application Firewall (WAF) for traffic inspection, API Gateway for authorization and routing, Secrets Manager for secure credential storage, and Lambda IAM roles for least-privilege compute access.
Why use Secrets Manager instead of Lambda environment variables?
Environment variables are visible in the Lambda console and can leak through logs or debugging. Secrets Manager encrypts secrets at rest, provides audit trails of access, supports automatic rotation, and scopes IAM permissions to specific secrets — giving you production-grade credential management.
How does Cognito authentication work with API Gateway?
Users authenticate with Cognito to receive a JWT token. The token is sent in the Authorization header with each API request. API Gateway has Cognito Authorizers that validate the token against the User Pool before allowing traffic to reach the Lambda backend. Invalid or expired tokens are rejected with a 401 response.
What improvements can I make to this setup?
Consider adding API keys for usage tracking, third-party API consumption patterns, API inventory documentation, and Infrastructure as Code (Terraform or CloudFormation) for reproducible deployments. These additions improve security posture, maintainability, and compliance readiness.
How much does this secure setup cost?
Cognito offers 50,000 MAU free. WAF costs $5/month per Web ACL plus $1/month per rule. API Gateway is $3.50 per million requests. Lambda bills per invocation and duration. Secrets Manager is $0.40 per secret per month. For a low-traffic API, total cost is typically under $15/month — far cheaper than the cost of a single security breach.
Deploying APIs Without Security Layers?
We'll audit your serverless API security, implement Cognito authentication, WAF protection, and Secrets Manager integration, then test the complete flow with authorized and unauthorized access. Stop leaving your APIs exposed.
