Protecting Your API & Best Practices

Connect Cognito to API Gateway so only signed-in users can call your backend.

1 min read

With an HTTP API, add a JWT authorizer:

  • Issuer: https://cognito-idp.<region>.amazonaws.com/<user-pool-id>
  • Audience: your app client ID

API Gateway now verifies every request's Authorization: Bearer <token> header before your Lambda runs. Invalid or expired tokens get a 401, and your code never sees them. Inside Lambda, read the verified claims:

Python
def lambda_handler(event, context):
    claims = event["requestContext"]["authorizer"]["jwt"]["claims"]
    user_id = claims["sub"]
    # ...only return this user's notes
How it flows
  1. 1User signs in

    Cognito returns tokens

  2. 2App calls API

    Authorization: Bearer token

  3. 3API Gateway

    Verifies JWT, else 401

  4. 4Lambda

    Reads claims.sub

Best practices

  • Turn on MFA (at least optional, with TOTP apps) and enable threat protection for suspicious sign-ins.
  • Use managed login or Amplify instead of building custom auth screens that handle passwords.
  • Offer social and enterprise sign-in (Google, Apple, SAML, OIDC) through user pool federation.
  • Use groups (e.g. admin, premium) and check cognito:groups in your API for authorization.
  • Keep token lifetimes short, and store tokens securely in the client.
Watch out

Authentication isn't authorization. A valid token proves who the user is. Your code must still check that user 123 can only read user 123's notes.

Key takeaways

  • A JWT authorizer on API Gateway rejects bad tokens before your code runs.
  • Read the verified `sub` claim to scope data to the current user.
  • Use MFA, managed login, federation, and groups, and always check ownership in your code.

Check your understanding

Pick an answer to see the explanation.

  1. 1. A request arrives with an expired token. With a JWT authorizer, what happens?

Next in “Make it production-ready”
You finished Cognito. Continue with the Secrets Manager tutorial