Skill 2.1.2

Implement access control (for example, fine-grained permissions, security tokens, MFA).

Key Concepts

Security tokens carry identity between components. Amazon Cognito user pools issue an ID token, an access token and a refresh token as JSON Web Tokens; AWS STS issues temporary credentials that include a session token. An API must verify a JWT's signature, expiry, issuer and audience before trusting its claims, and must never accept a token that was issued for another application.

Multi-factor authentication (MFA) adds a second factor to a password. Cognito user pools support SMS, email and time-based one-time password (TOTP) authenticator apps, set to optional or required, and adaptive authentication can demand MFA only for risky sign-ins. For AWS API access, an IAM policy can require MFA with the aws:MultiFactorAuthPresent condition key, and a developer obtains MFA-authenticated temporary credentials with sts get-session-token and the MFA device serial number and code.

Authorization decisions can use claims in the user's token, such as Cognito groups or custom attributes, checked in the application or in a Lambda authorizer. A Lambda authorizer can return an IAM policy that allows only the methods and resources the caller's groups permit, and API Gateway caches that decision for the token's TTL.

AWS can also enforce per-user data access directly. With Cognito identity pools, IAM policy conditions such as dynamodb:LeadingKeys restrict users to items whose partition key equals their identity ID, and s3:prefix or resource paths containing ${cognito-identity.amazonaws.com:sub} restrict them to their own S3 folder.

Cognito user pools issue an ID token (who the user is, for the client), an access token (what the user may do, with scopes, for APIs) and a refresh token (to obtain new tokens). Clients send the token in the Authorization header, and APIs verify its signature against the issuer's public keys (JWKS), its expiry, issuer and audience before trusting its claims.

API Gateway can validate tokens for you with a Cognito user pool authorizer (REST APIs), a JWT authorizer (HTTP APIs) or a Lambda authorizer for custom logic. Because anyone holding a bearer token can use it, tokens must only travel over HTTPS, should be short-lived and should never be logged.