Generated banner for AWS Auth
Generated logo for AWS Auth

AWS Auth

AWSOfficialPublished by AWS

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • No issues found

From the author

Adds user authentication to web and mobile apps with Amazon Cognito (user pools and identity pools) and the AWS Amplify client auth libraries. Covers sign-up/sign-in flows and the login page (Cognito-hosted UI / managed login), MFA, password policies, OAuth 2.0 / OIDC flows (auth-code + PKCE, client credentials), social/SAML federation, tokens (ID/access/refresh, rotation, revocation, storage), Cognito Lambda triggers, identity pools (temp AWS creds), and gating API Gateway (or ALB) routes to signed-in users via Cognito/JWT authorizers. Applies when adding a login or sign-up page, configuring a user pool or app client, choosing user pool vs identity pool, wiring social/SAML, refreshing tokens, requiring sign-in on an API Gateway or ALB, or debugging redirect_uri/token/MFA/CORS/federation errors. Does NOT cover Amplify Gen2 backend definitions (defineAuth, npx ampx → aws-amplify), IAM/STS/Identity Center (→ aws-iam), or API Gateway/Lambda resource config beyond the authorizer (→ aws-serverless).
— the description by AWS

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides guidance on integrating Amazon Cognito user pools and identity pools into web and mobile applications. It covers the full lifecycle of authentication, including sign-up/sign-in flows, managed login, MFA, OAuth 2.0/OIDC standards, and token management. It also details how to secure API Gateway or ALB routes using Cognito authorizers and how to vend temporary AWS credentials to clients via identity pools. The skill emphasizes secure practices, such as using PKCE for public clients and avoiding common pitfalls like client secret exposure or improper identity pool role configuration.

What it does

  • Configures Amazon Cognito user pools for user directory and authentication management.
  • Implements OAuth 2.0 and OIDC flows, including authorization code grant with PKCE.
  • Secures API Gateway and ALB routes using Cognito/JWT authorizers.
  • Manages identity pools to provide temporary AWS credentials to authenticated clients.
  • Handles token lifecycle, including rotation, revocation, and secure storage.
  • Integrates social and SAML federation for external identity providers.

When to use it

  • When adding sign-up or login functionality to a web or mobile application.
  • When you need to gate API endpoints to ensure only authenticated users can access them.
  • When your client application requires direct access to AWS services like S3 or DynamoDB.
  • When configuring MFA, password policies, or custom authentication challenges.
  • When troubleshooting authentication errors like redirect mismatches, CORS issues, or token validation failures.

Advantages

  • Provides clear distinctions between user pools and identity pools to prevent common architectural errors.
  • Highlights critical security practices like avoiding client secrets in public clients.
  • Includes specific guidance on avoiding destructive 'full replace' API calls.
  • Offers a structured approach to troubleshooting common authentication and federation issues.
  • Aligns with industry-standard security patterns for token handling and API protection.

Usage examples

“How do I set up a user pool for a React app with hosted UI?”
The agent provides steps to create a user pool, configure a public app client, enable the hosted UI with authorization code grant and PKCE, and wire the Amplify client library.
“My API Gateway is returning 401 errors for valid tokens, what should I check?”
The agent guides you to verify the token type, check the issuer and audience configuration in the JWT authorizer, and ensure the correct token is being sent in the Authorization header.
“How do I allow my mobile app users to upload files directly to S3?”
The agent explains how to set up an identity pool that trusts your user pool, maps authenticated users to an IAM role with S3 permissions, and vends temporary credentials.
“How do I add Google login to my Cognito user pool?”
The agent outlines the process of registering Google as an IdP in the user pool, mapping attributes, and updating the app client to include the provider.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/aws/aws-auth/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip aws-auth.zip -d .agents/skills

Documentation by AWS

AWS Auth (Amazon Cognito)

Application-level user authentication and authorization with Amazon Cognito and the Amplify client auth libraries. Verify specific limits, quotas, and exact API shapes against official AWS documentation when precision matters; trust the docs over memory when they conflict.

Recommended: The AWS MCP server provides streamlined access to the AWS APIs used in this skill (Cognito user pool/app client/identity pool setup, API Gateway authorizers). If it is unavailable, the AWS CLI commands shown throughout work directly — the skill has no hard dependency on MCP.

When NOT to use: Amplify Gen2 backend code (defineAuth, amplify/auth.ts, npx ampx); IAM policy/role/trust-policy authoring, STS, or IAM Identity Center console SSO; API Gateway route/integration setup or Lambda function implementation (this skill covers only the Cognito/JWT authorizer configuration and the purpose of Cognito Lambda triggers).

User Pool vs Identity Pool — pick first

These are different services that are frequently confused. Most apps need a user pool; add an identity pool only if the client must call AWS services directly.

You need...UseWhy
Sign-up / sign-in, user directory, issue JWTsUser poolIt authenticates users and is an OIDC IdP
The signed-in client to call S3/DynamoDB/etc. directly with AWS credentialsIdentity poolIt exchanges a token for temporary AWS credentials via STS
Both (sign in, then hit AWS resources from the browser/app)User pool → identity poolIdentity pool trusts the user pool as its IdP

If your app only calls your own backend/API, you do not need an identity pool — send the user pool token to your API. See identity-pools.md.

Critical Warnings

update-user-pool-client and set-identity-pool-roles are FULL REPLACE, not partial updates: Any field you omit is reset to its default — calling update-user-pool-client with only the fields you want to change silently wipes ExplicitAuthFlows, token validity, EnableTokenRevocation, refresh-token rotation, and read/write attributes; set-identity-pool-roles likewise replaces the whole roles + RoleMappings structure. Always read-modify-write: describe-user-pool-client (or get-identity-pool-roles) first, then re-send every existing field plus your change. In an agent context the wipe is invisible — the call succeeds and only breaks later when a user hits the missing flow. See managed-login-oauth.md and identity-pools.md.

Don't use the implicit grant for new apps: The implicit grant (response_type=token) is legacy and returns tokens in the URL fragment. Use the authorization code grant with PKCE (response_type=code + code_challenge) for SPAs and mobile — public clients, no client secret. See managed-login-oauth.md.

Don't store refresh tokens in localStorage for high-value apps: localStorage is readable by any injected script (XSS). The Amplify client library defaults to localStorage; switch to cookieStorage, keep refresh-token lifetime short, and enable refresh token rotation + token revocation on the app client. See tokens-and-sessions.md.

Access-token claim customization needs a paid feature plan: The pre token generation trigger customizes the ID token on the entry-level plan (V1), but customizing the access token (V2/V3) requires a paid feature plan — check the Cognito feature plans documentation for which plan currently includes this, as plan names and inclusions can change. Don't assume access-token claims work on the entry-level plan. See lambda-triggers.md.

App client secret + SPA = broken auth: A public client (browser/mobile) must have no client secret. If a secret is set, token calls fail unless a SECRET_HASH is sent, which a browser cannot protect. Generate a secret only for confidential (server-side) clients.

Don't bulk admin-confirm-sign-up UNCONFIRMED users: When users are stuck UNCONFIRMED, prefer resend-confirmation-code so each user re-verifies via confirm-sign-up and proves email ownership (the code likely expired or went to spam). admin-confirm-sign-up flips the status instantly but confirms the account without verifying the email — the attribute stays unverified, which is dangerous when email drives password reset or account linking. Reserve it for trusted/migrated accounts. See troubleshooting.md.

Quick Navigation

You want to...Go to
Create a user pool, sign-up/sign-in, MFA, password policy, app clientsuser-pools.md
Add hosted UI / managed login, OAuth flows, social or SAML login, callback URLs, custom domain (ACM in us-east-1)managed-login-oauth.md
Handle ID/access/refresh tokens, rotation, revocation, session termination (global sign-out vs revoke vs disable)tokens-and-sessions.md
Give the client temporary AWS credentials, guest access, role mappingidentity-pools.md
Protect an API Gateway API with Cognito tokens (and enforce custom claims in the backend)api-authorization.md
Add Cognito login in front of an Application Load Balancer (ALB authenticate-cognito)api-authorization.md
Machine-to-machine (client credentials) auth, resource servers, custom scopesmanaged-login-oauth.md
Create user pool groups and add users to them (cognito:groups, Precedence)user-pools.md
Customize claims, custom auth challenge flows, migrate users, validate sign-uplambda-triggers.md
Add passkey / WebAuthn sign-in (USER_AUTH flow, AllowedFirstAuthFactors, WebAuthn enrollment)passkeys.md
Configure threat protection — compromised-credentials block, adaptive auth (risk-based MFA), log delivery to CloudWatchthreat-protection.md
Something is broken (redirect, token, MFA, CORS, social login)troubleshooting.md

Common Workflows

"Add sign-up and login to my React app" → Create a user pool + a public app client (no secret), enable the hosted UI / managed login with the authorization code grant with PKCE, wire the Amplify client library. See user-pools.md and managed-login-oauth.md.

"Add Google / social login" → Register the social IdP on the user pool, map attributes, add the provider to the app client and hosted UI. See managed-login-oauth.md.

"Only authenticated users should call my API" → HTTP API → JWT authorizer; REST API → Cognito user pools authorizer. See api-authorization.md.

"Let the browser upload to S3 after login" → User pool for sign-in, then an identity pool to vend scoped temporary credentials. See identity-pools.md.

Troubleshooting

Error/SymptomLikely CauseQuick Fix
redirect_mismatch / redirect to wrong URL after loginCallback URL not registered, or scheme/trailing-slash/case differsAdd the exact callback URL (incl. scheme and path) to the app client's Allowed callback URLs
Token calls fail with "unable to verify secret hash"Client secret set on a public (SPA/mobile) clientRecreate the app client with no secret, or send SECRET_HASH from a confidential client
Users get 401 from API Gateway with a valid tokenWrong token type or audience/issuer mismatchHTTP JWT authorizer: issuer https://cognito-idp.{region}.amazonaws.com/{userPoolId}, audience = app client id; send the token the authorizer expects
CORS errors calling the hosted UI / token endpointBrowser calling /oauth2/token cross-origin, or missing CORS on your APIDo the code exchange with PKCE; don't proxy the token endpoint from the browser
Social login user "already exists" / attribute conflictSame email across providers creates separate usersEnable attribute mapping + account linking; treat email as non-unique across IdPs

Full tables in troubleshooting.md.

Security Considerations

  • Public clients (SPA/mobile): no client secret, authorization code grant with PKCE, request least-privilege scopes.

  • Enable MFA (TOTP or SMS), a strong password policy, and advanced security / threat protection where available.

  • Short access-token lifetime; enable refresh token rotation and token revocation; prefer cookieStorage over localStorage.

  • Identity pools: scope the authenticated IAM role tightly; disable unauthenticated (guest) access unless required.

  • Validate JWTs against the user pool JWKS (iss, aud/client_id, token_use, exp) on every protected request. Use a maintained library such as aws-jwt-verify rather than hand-rolling verification.

  • Set security headers on the app's web pages: Content-Security-Policy (restrict script sources to mitigate token-stealing XSS), Strict-Transport-Security (HSTS), X-Frame-Options/frame-ancestors (clickjacking on login pages), and X-Content-Type-Options: nosniff.

  • Enable logging and monitoring: CloudTrail for Cognito API events (sign-up/sign-in/admin), user pool threat protection (adaptive auth + event logging), CloudWatch alarms on failed/throttled auth, and API Gateway access logging for authorizer decisions.

  • All Cognito and API endpoints are HTTPS/TLS only; enable encryption at rest with a customer-managed KMS key (and restricted key access) on CloudWatch Log groups, SNS topics used for MFA/notifications, and any identity-pool-fronted upload buckets.

  • If using SNS for MFA/notification delivery, enable server-side encryption (KMS) on the topic, and keep SMS/email message content limited to what the recipient needs — don't include more PII than the message requires.

  • References: Amazon Cognito security features (user pools), Amazon Cognito security (top-level, incl. identity pools), and IAM/STS best practices.

Where to Look When This Skill Is Silent

When you need depth beyond this skill — exact parameter shapes, current limits, edge behaviors — fall back to the authoritative AWS sources rather than guessing. Pointers age much slower than content, so this map stays useful without the skill having to grow.

Not Covered By This Skill

  • Amplify Gen2 backend (defineAuth, amplify/auth.ts, npx ampx sandbox).

  • IAM policy/role/trust-policy authoring, STS, IAM Identity Center console SSO.

  • API Gateway route/integration setup and Lambda function implementation (this skill covers only the Cognito/JWT authorizer configuration and the purpose of Cognito Lambda triggers).

Files

references/tokens-and-sessions.md

Tokens & Sessions

Overview

Cognito issues three JWTs after authentication. Knowing which token to use where — and how to refresh, rotate, revoke, and store them safely — prevents most auth bugs.

The three tokens

TokenContentsUse it forLifetime
ID tokenIdentity claims (name, email, etc.)Proving who the user is (identity) to your app; identity-based checks you run yourself. NOT the credential for scope-based API authorizationShort-lived, configurable per app client — check the current default and valid range in the Cognito quotas docs or via aws cognito-idp describe-user-pool-client
Access tokenGroups, scopes, user claimsAuthorizing API calls — scope- and group-based access to your API and OAuth-scoped resources. This is the token meant for authorizationShort-lived, configurable per app client — check the current default and valid range in the Cognito quotas docs or via aws cognito-idp describe-user-pool-client
Refresh tokenOpaqueGetting new ID and access tokens without re-loginLong-lived, configurable per app client — check the current default and min/max range in the Cognito quotas docs or via aws cognito-idp describe-user-pool-client

ID and access tokens are short-lived; the refresh token is long-lived. Send the token your consumer expects: an API Gateway JWT authorizer can be configured for either, but the audience (aud) claim is present on the ID token while the access token carries client_id and scope — match the authorizer's audience/identity source to the token you send. See api-authorization.md.

For authorization decisions, use the access token — it carries scope and cognito:groups, so scope- or group-based checks belong there. The ID token proves identity and is fine for identity-based checks you perform inside your own app, but it is not the token to gate API access with.

InitiateAuth-issued access tokens don't carry custom scopes

An important architectural fact: InitiateAuth and AdminInitiateAuth issue access tokens that carry only the reserved scope aws.cognito.signin.user.admin — custom scopes are NEVER included regardless of what's configured in the app client's AllowedOAuthScopes. This is independent of the auth flow (SRP, USER_PASSWORD_AUTH, USER_AUTH — all the same). Custom scopes are only issued through the OAuth 2.0 endpoints: /oauth2/authorize (hosted UI / managed-login authorization-code + PKCE flow) and /oauth2/token (for token-grant endpoints including client_credentials).

If your API Gateway route requires a custom scope like https://api.example.com/orders.read, an InitiateAuth-signed user cannot pass it — the scope is simply not in their access token. Three workarounds:

  1. Switch the sign-in flow to hosted UI / OAuth (authorization-code + PKCE) — the standard fix.

  2. Authorize on cognito:groups (or a custom claim) at the API instead of on scopes.

  3. Use a V2/V3 pre-token-generation Lambda trigger to inject scopes into the access token via scopesToAdd — requires the Essentials or Plus feature plan (V3 for machine-to-machine).

Adding the scope to AllowedOAuthScopes on the app client does NOT fix this — the config is already relevant only to the OAuth endpoints.

Refresh token rotation

Enable rotation so each refresh returns a new refresh token and invalidates the old one, limiting the blast radius of a stolen token.

aws cognito-idp update-user-pool-client \
  --user-pool-id <pool-id> --client-id <client-id> \
  --refresh-token-rotation Feature=ENABLED,RetryGracePeriodSeconds=30

update-user-pool-client is a full replace, not a partial update — any field you omit reverts to its default. The one-flag command above is safe only on a client that has no other configuration to lose. On an already-configured client, describe it first and re-send every existing field alongside the rotation flag, or you will silently wipe its auth flows, token validity, and scopes. See the read-modify-write pattern in managed-login-oauth.md.

  • RetryGracePeriodSeconds (0–60) lets the rotated-out token stay valid briefly for client retries. 0 invalidates it immediately on a successful refresh.

  • Refresh with the GetTokensFromRefreshToken API (or the token endpoint grant_type=refresh_token).

  • Rotation disables the REFRESH_TOKEN_AUTH flow. An app client with rotation enabled cannot use InitiateAuth/AdminInitiateAuth with AuthFlow=REFRESH_TOKEN_AUTH — that call is rejected at runtime. So ALLOW_REFRESH_TOKEN_AUTH and refresh-token rotation are not a valid combination: leave ALLOW_REFRESH_TOKEN_AUTH out of the client's --explicit-auth-flows when rotation is on, and refresh via GetTokensFromRefreshToken (or the token endpoint) instead.

Session termination — pick the right API

Three APIs end sessions, each with different reach:

APIWhat it killsUse for
RevokeToken / /oauth2/revokeONE refresh token + the access/ID tokens issued from itSigning out a single device
AdminUserGlobalSignOutAll refresh tokens for the user (across every session)Stolen device / password compromise
AdminDisableUserAll tokens AND blocks future auth attemptsAccount termination / suspected compromise

RevokeToken requires token revocation enabled on the app client (EnableTokenRevocation=true). Revoking a refresh token invalidates every access/ID token issued from it; other refresh tokens for the same user are unaffected. AdminUserGlobalSignOut invalidates the user's identity, access, and refresh tokens across all sessions — but the user's account is still active, so they can sign back in and get fresh tokens. AdminDisableUser goes further: existing tokens die AND new auth attempts fail (NotAuthorizedException: User is disabled).

Nuance: access tokens against non-Cognito resource servers

All three APIs invalidate server-side session state. When a downstream resource server verifies the token:

  • Cognito's own user-pool APIs check revocation state and reject revoked tokens immediately.

  • External resource servers that verify the JWT locally (signature + exp + iss + aud) have no way to know a token was revoked. Already-issued access tokens remain usable against those servers until natural exp.

The mitigation is short access-token lifetimes (5–15 minutes) plus refresh-token revocation for the long-tail lockout — force the client to refresh, at which point the revoked refresh token blocks the flow.

Signing out via any of the three APIs above does not clear the managed-login session cookie. A user with a valid cookie can hit /oauth2/authorize and receive fresh tokens without ever presenting a refresh token — so a "kill all sessions" flow that only calls AdminUserGlobalSignOut leaves that back door open. For a full teardown, also redirect the user through:

https://<domain>/logout?client_id=<id>&logout_uri=<url>

The /logout endpoint clears the cookie and returns the user to logout_uri (which must be registered as an Allowed sign-out URL on the app client).

Token revocation (single-session detail)

Enable revocation on the app client so any of the APIs above can invalidate a session. Revocation adds jti / origin_jti claims to issued tokens, slightly increasing token size.

aws cognito-idp update-user-pool-client \
  --user-pool-id <pool-id> --client-id <client-id> \
  --enable-token-revocation \
  ... (re-send every other existing field — full-replace API)

Revoke via the API:

aws cognito-idp revoke-token \
  --client-id <client-id> \
  --token <refresh-token>

Or the OAuth endpoint (for public clients that don't want to expose the API):

POST https://<domain>/oauth2/revoke
Content-Type: application/x-www-form-urlencoded

client_id=<id>&token=<refresh-token>

Frontend token storage (security)

The Amplify client library defaults to localStorage, which is readable by any injected script — an XSS foothold can exfiltrate tokens. For anything sensitive:

  • Prefer cookieStorage with Secure and SameSite=Strict. Note that Amplify's cookie store cannot be HttpOnly — the SDK reads tokens client-side to attach them to requests, so setting HttpOnly would break token retrieval. For true HttpOnly storage, use a backend-for-frontend (BFF) that holds tokens server-side.

  • Keep the refresh token lifetime short and enable rotation + revocation.

  • Never place tokens in URLs or logs.

There is no perfect browser storage; reducing token lifetime and enabling rotation/revocation matters more than the storage location alone.

Amplify client library (using an existing user pool)

This is the client SDK (aws-amplify / @aws-amplify/auth) pointed at a user pool you configured — not the Amplify Gen2 backend (amplify/auth.ts), which belongs to the aws-amplify skill.

import { Amplify } from 'aws-amplify';
import { signIn, signInWithRedirect, fetchAuthSession } from 'aws-amplify/auth';

Amplify.configure({
  Auth: { Cognito: { userPoolId: '<pool-id>', userPoolClientId: '<client-id>' } },
});

// Direct SRP / username-password sign-in (your own UI, no hosted UI):
await signIn({ username, password });

// Hosted UI / managed login via the OAuth authorization-code + PKCE flow:
await signInWithRedirect();   // redirects to the hosted UI; Amplify completes the code+PKCE exchange on return

const { tokens } = await fetchAuthSession();   // tokens.idToken / tokens.accessToken

signIn({ username, password }) runs the SRP / username-password flow directly against the user pool — it does not use the hosted UI or the OAuth code+PKCE exchange. The hosted-UI authorization-code + PKCE flow goes through signInWithRedirect(); that is the call that performs the code+PKCE exchange. Either way, Amplify handles token storage and automatic refresh.

Common Errors

ErrorCauseFix
Users forced to re-login every hourNot refreshing; only using ID/access tokenUse the refresh token (or Amplify auto-refresh) to get new tokens
NotAuthorizedException: Refresh Token has been revokedRotation invalidated the old tokenStore and use the newest refresh token from each refresh
Token accepted then suddenly rejectedRevocation or expiryRe-authenticate; check exp and revocation state

Authoritative sources

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs Node.js

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
AWS
Publisher
AWS (Official)
Source
aws/agent-toolkit-for-aws · skills/core-skills/aws-auth · commit 0a218f8
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • NOTICE (added by AutoGineer from NOTICE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
aws/agent-toolkit-for-aws

AutoGineer is not affiliated with or endorsed by AWS or AWS.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-auth.zip