123DevOps··9 min read

How to configure AWS Cognito to protect apps on EKS: user pool, managed login, PKCE, and JWT

Set up a Cognito user pool with Terraform and with the AWS CLI (an app client with code flow + PKCE, a domain, groups, and MFA), then see how an app on EKS consumes the tokens: JWT validation, an ALB with authenticate-cognito, and API Gateway.

Kubernetes

Getting an application onto EKS is the easy part. The question that follows right away is: who is allowed in? Writing sign-in, password recovery, MFA, and token issuance inside every microservice is expensive and risky. Amazon Cognito provides all of that as a managed service: a user directory that acts as an OpenID Connect provider and issues JWTs that your cluster, your ALB, or your API Gateway know how to validate. In this guide we build the same setup two ways, Terraform and the AWS CLI, and then wire Cognito into the applications running on Kubernetes.

User pool or identity pool?

The name “Cognito” covers two different products, and mixing them up is behind a lot of broken designs.

User pool Identity pool
What it is for Authentication: user directory and OIDC IdP Temporary AWS credentials via STS
What it returns ID token, access token, and refresh token (JWT) Access key, secret key, and session token
Federation SAML, OIDC, and social providers Accepts tokens from the user pool and other IdPs
Anonymous access No Yes (guest access)
Typical EKS use case Protecting APIs and front ends A mobile app that calls S3 or DynamoDB directly

To protect an API running in the cluster, you almost always need only the user pool. The identity pool comes in when the client itself (a browser or mobile app) has to call AWS services directly. Pods that need AWS credentials use EKS Pod Identity, not an identity pool (see how to install EKS with Terraform).

Feature plans and managed login

User pools come in feature plans: Lite, Essentials, and Plus. According to the current documentation, managed login, the new hosted sign-in page with a visual branding editor, passkeys, and localization, requires the Essentials or Plus plan; Lite keeps the “classic hosted UI.” Essentials is the default for new pools. Plans and what each one includes change fairly often, so check the feature plans page in the Cognito documentation before you decide.

Two practical details:

  • On the pool’s domain, managed_login_version = 2 turns on managed login; 1 keeps the classic UI.
  • App clients created through the API (Terraform and the CLI included) need a branding style (CreateManagedLoginBranding) before managed login works for them. Without it, the sign-in page does not show up for that client.

Configuring with Terraform

The code below uses the hashicorp/aws 6.x provider (validated with 6.74.0 via terraform validate). It creates the pool with TOTP MFA, the domain with managed login, two app clients, the branding, and two groups.

resource "aws_cognito_user_pool" "this" {
  name                     = "your-org-prod"
  user_pool_tier           = "ESSENTIALS" # managed login requires Essentials or Plus
  deletion_protection      = "ACTIVE"
  username_attributes      = ["email"]
  auto_verified_attributes = ["email"]

  mfa_configuration = "OPTIONAL"
  software_token_mfa_configuration {
    enabled = true # TOTP (authenticator app)
  }

  password_policy {
    minimum_length    = 12
    require_lowercase = true
    require_uppercase = true
    require_numbers   = true
    require_symbols   = true
  }

  account_recovery_setting {
    recovery_mechanism {
      name     = "verified_email"
      priority = 1
    }
  }
}

resource "aws_cognito_user_pool_domain" "this" {
  domain                = "your-org-auth" # your-org-auth.auth.<region>.amazoncognito.com
  user_pool_id          = aws_cognito_user_pool.this.id
  managed_login_version = 2
}

# Public client (SPA): no secret, code flow + PKCE
resource "aws_cognito_user_pool_client" "spa" {
  name                                 = "web-spa"
  user_pool_id                         = aws_cognito_user_pool.this.id
  generate_secret                      = false
  allowed_oauth_flows_user_pool_client = true
  allowed_oauth_flows                  = ["code"]
  allowed_oauth_scopes                 = ["openid", "email", "profile"]
  supported_identity_providers         = ["COGNITO"]
  callback_urls                        = ["https://app.example.com/callback"]
  logout_urls                          = ["https://app.example.com/"]
  explicit_auth_flows                  = ["ALLOW_REFRESH_TOKEN_AUTH"]
  prevent_user_existence_errors        = "ENABLED"
  enable_token_revocation              = true

  access_token_validity  = 60
  id_token_validity      = 60
  refresh_token_validity = 7
  token_validity_units {
    access_token  = "minutes"
    id_token      = "minutes"
    refresh_token = "days"
  }
}

# Confidential client for the ALB (authenticate-cognito requires a secret)
resource "aws_cognito_user_pool_client" "alb" {
  name                                 = "alb-eks"
  user_pool_id                         = aws_cognito_user_pool.this.id
  generate_secret                      = true
  allowed_oauth_flows_user_pool_client = true
  allowed_oauth_flows                  = ["code"]
  allowed_oauth_scopes                 = ["openid", "email"]
  supported_identity_providers         = ["COGNITO"]
  callback_urls                        = ["https://app.example.com/oauth2/idpresponse"]
}

resource "aws_cognito_managed_login_branding" "spa" {
  user_pool_id                = aws_cognito_user_pool.this.id
  client_id                   = aws_cognito_user_pool_client.spa.id
  use_cognito_provided_values = true
}

resource "aws_cognito_user_group" "admins" {
  name         = "admins"
  user_pool_id = aws_cognito_user_pool.this.id
  description  = "Application administrators"
  precedence   = 1
}

resource "aws_cognito_user_group" "readers" {
  name         = "readers"
  user_pool_id = aws_cognito_user_pool.this.id
  precedence   = 10
}

data "aws_region" "current" {}

output "issuer" {
  value = "https://cognito-idp.${data.aws_region.current.region}.amazonaws.com/${aws_cognito_user_pool.this.id}"
}

App client: code flow + PKCE

The recommended flow is authorization code. For public clients (SPA, mobile app, CLI), use it with PKCE: the client generates a random code_verifier, sends its hash (code_challenge, method S256) on the way to /oauth2/authorize, and presents the original verifier when it exchanges the code at /oauth2/token. Anyone who intercepts the code cannot redeem it without the verifier. There is no PKCE “switch” on the client: the front end’s OIDC library implements it, and Cognito validates it.

The other flows have narrow uses. implicit returns tokens straight in the URL and should not be used in new apps. client_credentials is for machine-to-machine: it requires a secret, uses custom scopes only, and must be the client’s only flow. Also remember that a secret cannot be added later: if the client was created as public, create another one.

Groups and MFA

Groups show up in the cognito:groups claim in both the ID token and the access token, which enables simple authorization in the app (“only admins can call DELETE”). Each group can have one IAM role, and precedence decides which one becomes cognito:preferred_role. Groups cannot be nested.

For MFA, OPTIONAL with TOTP is a good start: users enable an authenticator app and the application can require MFA for sensitive areas. ON forces everyone to enroll in MFA before their first sign-in.

The same setup with the AWS CLI

The commands and flags below were checked with aws cognito-idp <command> help. One detail the help makes clear: create-user-pool only accepts SMS MFA settings; for TOTP, create the pool first and then use set-user-pool-mfa-config.

REGION=us-east-1

POOL_ID=$(aws cognito-idp create-user-pool --region "$REGION" \
  --pool-name your-org-prod \
  --user-pool-tier ESSENTIALS \
  --username-attributes email \
  --auto-verified-attributes email \
  --deletion-protection ACTIVE \
  --query 'UserPool.Id' --output text)

aws cognito-idp set-user-pool-mfa-config --user-pool-id "$POOL_ID" \
  --software-token-mfa-configuration Enabled=true \
  --mfa-configuration OPTIONAL

aws cognito-idp create-user-pool-domain --user-pool-id "$POOL_ID" \
  --domain your-org-auth --managed-login-version 2

CLIENT_ID=$(aws cognito-idp create-user-pool-client --user-pool-id "$POOL_ID" \
  --client-name web-spa --no-generate-secret \
  --allowed-o-auth-flows code --allowed-o-auth-flows-user-pool-client \
  --allowed-o-auth-scopes openid email profile \
  --supported-identity-providers COGNITO \
  --callback-urls https://app.example.com/callback \
  --logout-urls https://app.example.com/ \
  --access-token-validity 60 --id-token-validity 60 --refresh-token-validity 7 \
  --token-validity-units AccessToken=minutes,IdToken=minutes,RefreshToken=days \
  --enable-token-revocation --prevent-user-existence-errors ENABLED \
  --query 'UserPoolClient.ClientId' --output text)

aws cognito-idp create-managed-login-branding --user-pool-id "$POOL_ID" \
  --client-id "$CLIENT_ID" --use-cognito-provided-values

aws cognito-idp create-group --user-pool-id "$POOL_ID" \
  --group-name admins --precedence 1

aws cognito-idp admin-create-user --user-pool-id "$POOL_ID" \
  --username [email protected] \
  --user-attributes Name=email,[email protected] Name=email_verified,Value=true \
  --desired-delivery-mediums EMAIL

aws cognito-idp admin-add-user-to-group --user-pool-id "$POOL_ID" \
  --username [email protected] --group-name admins

admin-create-user sends an invitation with a temporary password; on first sign-in the user sets their own password. To import users without an invitation email, there is --message-action SUPPRESS.

How the app on EKS consumes Cognito

There are three places where the token can be validated. Pick one as the main gate and avoid duplicating authorization rules across all of them.

Validating the JWT in the application

The endpoints follow a fixed format:

Issuer: https://cognito-idp.<region>.amazonaws.com/<userPoolId>
JWKS:   https://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/jwks.json
OIDC:   https://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/openid-configuration
Token:  https://your-org-auth.auth.<region>.amazoncognito.com/oauth2/token

With a mature JWT library, verify the signature with the JWKS key (by kid), plus iss, exp, and token_use (access or id). The access token has no aud: check client_id instead. On the ID token, check aud. Cache the JWKS instead of fetching it on every request.

ALB with authenticate-cognito

With the AWS Load Balancer Controller, the ALB itself handles sign-in before the request reaches the pod. The authenticate-cognito action works on HTTPS listeners only, and the app client needs a secret, the code flow, and the callback https://<your-domain-or-alb-dns>/oauth2/idpresponse. The annotation names below belong to the controller; check the docs for the version you run.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app
  namespace: shop
  annotations:
    alb.ingress.kubernetes.io/scheme: internet-facing
    alb.ingress.kubernetes.io/target-type: ip
    alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS":443}]'
    alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:us-east-1:111122223333:certificate/abc
    alb.ingress.kubernetes.io/auth-type: cognito
    alb.ingress.kubernetes.io/auth-idp-cognito: '{"userPoolARN":"arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_EXAMPLE","userPoolClientID":"<alb-client-id>","userPoolDomain":"your-org-auth"}'
    alb.ingress.kubernetes.io/auth-scope: openid email
    alb.ingress.kubernetes.io/auth-on-unauthenticated-request: authenticate
spec:
  ingressClassName: alb
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: app
                port:
                  number: 80

The pod receives the x-amzn-oidc-data header, a JWT signed with ES256 by the ALB. Verify that signature in the application. Also make sure the pod only accepts traffic coming from the ALB, using security groups and NetworkPolicy; otherwise anyone inside the VPC can forge the header. This manifest passed kubectl apply --dry-run=server in the lab, but without the controller and without AWS; the ALB behavior itself was not tested.

API Gateway with a JWT authorizer

If the API sits behind API Gateway, the HTTP API JWT authorizer validates the token before the request enters the VPC. The issuer is the same as above and the audience is the client ID (for access tokens, API Gateway checks client_id). The step-by-step guide, with a VPC link to an internal EKS ALB, is in how to configure API Gateway.

Security: tokens and public clients

  • Never put a client secret in an SPA or mobile app. Everything shipped to the browser is public. Use a public client + PKCE, and keep secrets for backends, the ALB, and client_credentials.
  • Short-lived tokens. Access and ID tokens of 60 minutes (or less) and a refresh token lifetime that matches the risk. AWS sets minimums and maximums for each token; check the current docs.
  • Revocation turned on (enable_token_revocation) and a logout that calls the revocation endpoint.
  • prevent_user_existence_errors so you don’t reveal which emails exist.
  • Deletion protection on the production pool.
  • Authorization in the application. Cognito tells you who the user is; what they can do is your call, based on groups and scopes.

Checklist

  • User pool on the right plan (Essentials or Plus if you’ll use managed login)
  • Domain with managed_login_version = 2 and branding created for each client
  • SPA as a public client with code flow + PKCE, no secret
  • Groups defined and checked in the app through cognito:groups
  • TOTP MFA enabled (at least OPTIONAL)
  • JWT validation covering iss, exp, token_use, and client_id/aud
  • Token lifetimes reviewed and revocation enabled

Identity is infrastructure: configure Cognito as code, validate tokens in one place, and never hand a secret to the browser.

Get updates on new posts and stay in the loop!