How do you implement authentication in a serverless API?

Answer

Authentication in serverless APIs uses one of three approaches: (1) Lambda Authorizer (API Gateway custom authorizer) — a Lambda function that validates the token from the Authorization header and returns an IAM policy allowing/denying access. Token-based (validates JWT/OAuth token) or request-based (validates any request parameter). Results are cached by API Gateway for a configurable TTL; (2) Amazon Cognito User Pools — configure API Gateway to validate Cognito JWTs natively without a Lambda Authorizer. Users authenticate with Cognito, receive a JWT, and include it in API requests. Fully managed identity provider with MFA, social login, SAML; (3) JWT validation in function — the Lambda function itself validates JWTs using a library (jsonwebtoken, PyJWT). Simpler but adds latency to every request. Best practice: use Lambda Authorizer with caching for custom auth logic, Cognito for standard user management, and JWT validation in function for simple internal APIs.