Skip to content
WritingArticle
  • #serverless
  • #aws
  • #security
  • #api-gateway
  • #cognito

Secure Your Serverless API on AWS: Least-Privilege IAM, Cognito JWT Authorizers, Secrets and Throttling

Pawan Joshi

6 min read

Share
Cover image for “Secure Your Serverless API on AWS: Least-Privilege IAM, Cognito JWT Authorizers, Secrets and Throttling”

Serverless removes a lot of security work: no operating systems to patch, no open SSH ports. It doesn't remove all of it. Your code, permissions and configuration are still your responsibility.

This is the checklist I use to secure a serverless API on AWS, from most important to least. Each step includes the configuration to copy.

Quick summary

  • Give every function its own least-privilege role.
  • Require sign-in with a JWT authorizer and read the user ID from verified claims.
  • Validate input, keep secrets in Secrets Manager, throttle the API and limit CORS to your domain.

Five security layers in a row that a request passes through: throttling, JWT authorizer, validation, least-privilege role and secrets, with what each layer stops listed underneathA request must pass every layer before it reaches your function and your data.

The shared responsibility, simply

AWS securesYou secure
The servers, network and runtime patchesWho can call your API
Lambda's isolation between customersWhat your function is allowed to do (IAM)
The physical data centersYour code, input validation and dependencies
Encryption featuresTurning them on and managing secrets

1. Give every function least-privilege permissions

Each Lambda function runs with an execution role. If that role can do everything, a bug in your code can do everything too.

Grant only the actions the function needs, on only the resources it uses. AWS SAM policy templates make this easy:

CreateNoteFunction:
  Type: AWS::Serverless::Function
  Properties:
    Handler: create.handler
    Policies:
      - DynamoDBWritePolicy:
          TableName: !Ref NotesTable     # write to one table, nothing else

Avoid policies like AmazonDynamoDBFullAccess or "Action": "*". Use one role per function so a read-only function can never delete data.

Comparison of one broad shared role that lets any function do anything with one role per function that grants each only what it needs, such as writing one table or reading one secretOne role per function means a bug can only reach that function's small job.

2. Require sign-in with a JWT authorizer

Don't leave write endpoints open to the internet. HTTP APIs in API Gateway support JWT authorizers, which check a token before your function even runs.

With Amazon Cognito as the identity provider:

NotesApi:
  Type: AWS::Serverless::HttpApi
  Properties:
    Auth:
      DefaultAuthorizer: CognitoJwt
      Authorizers:
        CognitoJwt:
          IdentitySource: $request.header.Authorization
          JwtConfiguration:
            issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPool}
            audience:
              - !Ref UserPoolClient

Invalid or missing tokens get a 401 from API Gateway, so your function never runs and you don't pay for it.

Flow of a JWT authorizer: the client signs in with Cognito and receives a token, calls API Gateway with an Authorization header, API Gateway verifies the token, a valid token reaches Lambda with verified claims and an invalid one returns 401 without running LambdaAPI Gateway checks the token first. Bad tokens never reach your code.

Inside the function, read the user's ID from the verified claims, never from the request body:

export const handler = async (event) => {
  const userId = event.requestContext.authorizer.jwt.claims.sub;   // verified by API Gateway
  // Store and query notes under this userId only.
};

That last line prevents a classic bug: a user changing an ID in the request to read someone else's data.

3. Validate every input

Treat all input as untrusted: the body, path parameters, query strings and headers.

  • Check types, required fields and lengths.
  • Reject unknown fields.
  • Return a clear 400 for bad input.
function parseNote(body) {
  const input = JSON.parse(body ?? "{}");
  const text = typeof input.text === "string" ? input.text.trim() : "";
  if (!text || text.length > 1000) throw new ValidationError("text must be 1-1000 characters");
  return { text };
}

For larger APIs, use a schema library such as Zod, or Powertools for AWS Lambda's validation utility.

4. Keep secrets out of code and plain environment variables

API keys and database passwords don't belong in Git or in plain-text environment variables.

  • Store them in AWS Secrets Manager or SSM Parameter Store (SecureString).
  • Give the function permission to read only that secret.
  • Read it once and cache it, so you don't call Secrets Manager on every request.
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const secrets = new SecretsManagerClient({});
let cachedKey;
 
async function emailApiKey() {
  if (!cachedKey) {
    const { SecretString } = await secrets.send(new GetSecretValueCommand({ SecretId: "notes/email-api-key" }));
    cachedKey = SecretString;
  }
  return cachedKey;
}

The AWS Parameters and Secrets Lambda Extension can also cache secrets for you.

5. Throttle the API

Throttling protects both your backend and your bill. Set a default limit on the HTTP API stage:

NotesApi:
  Type: AWS::Serverless::HttpApi
  Properties:
    DefaultRouteSettings:
      ThrottlingRateLimit: 20      # requests per second
      ThrottlingBurstLimit: 40

You can also set reserved concurrency on a function to cap how many copies run at once, so one busy endpoint can't use all your account's concurrency.

For public endpoints like sign-up forms, put AWS WAF in front of CloudFront or API Gateway to block abusive traffic.

6. Configure CORS for your domain only

If a browser app calls the API, allow only your own origin:

CorsConfiguration:
  AllowOrigins:
    - https://pawanjoshi.dev
  AllowMethods: [GET, POST, DELETE]
  AllowHeaders: [authorization, content-type]

Avoid * for APIs that use credentials. CORS isn't authentication, but a tight configuration stops other websites from calling your API from users' browsers.

7. Encrypt and protect data

  • DynamoDB and S3 encrypt data at rest by default. Use a customer managed KMS key if you need control over the key.
  • Keep S3 Block Public Access on. Serve files through CloudFront with Origin Access Control instead of public buckets.
  • Turn on DynamoDB point-in-time recovery for tables you can't afford to lose.

8. Log safely and watch for problems

  • Log in structured JSON, with a request ID on every line.
  • Never log tokens, passwords or full personal data.
  • Turn on AWS CloudTrail to record who changed what in your account.
  • Create CloudWatch alarms on API 4xx and 5xx spikes and Lambda errors. A sudden rise in 401s or 403s can mean someone is probing your API.

9. Keep dependencies clean

Most vulnerabilities come from packages, not your own code.

  • Run npm audit (or your language's equivalent) in CI and fix high-severity issues.
  • Keep the dependency list short. Every package is code you're trusting.
  • Update runtimes before they reach end of support.

The checklist

  1. One least-privilege role per function.
  2. JWT authorizer on every endpoint that isn't public.
  3. User identity from verified token claims, never from the body.
  4. Validate every input.
  5. Secrets in Secrets Manager or Parameter Store, cached.
  6. Throttling on the API, reserved concurrency where needed, WAF for public forms.
  7. CORS limited to your domain.
  8. Encryption on, public access blocked, backups enabled.
  9. Safe structured logs, CloudTrail, alarms.
  10. Dependencies audited in CI.

Build the API first in Build a Serverless REST API with AWS Lambda, API Gateway and DynamoDB, then apply this checklist to it.

Found this useful?

Share it with your group