Skip to Content
Cloud Engineering Academy
4. API Development & Integration

Amazon Cognito user pools: app clients, resource servers and scopes

Create a Cognito user pool with a resource server, custom scopes and app clients, get real access tokens, and configure the Account Information API to accept only the right ones.

intermediate⏱ 1 h 30 min🟢 FreeDVA-C03SAA-C03SCS-C03

Assumes: .NET 10 LTS · AWS SDK for .NET v4 · AWS CLI v2 · Amazon.CDK.Lib 2.277.0 · Microsoft.AspNetCore.Authentication.JwtBearer 10.0.15 · Region us-east-1. Verified against official sources on 2026-11-17.

Learning objectives

By the end of this lesson you can:

  • Explain the difference between a Cognito user pool and an identity pool, and pick the right feature plan (Lite, Essentials, Plus).
  • Create a user pool, domain, resource server with custom scopes, a public app client (PKCE) and a confidential app client (client credentials) with the CLI and CDK (C#).
  • Read every claim in a Cognito access token and explain why it has no aud by default.
  • Configure ASP.NET Core JwtBearer to accept only Cognito access tokens from allow-listed app clients.

Prerequisites

Why this matters in banking

Harbourline's mobile app, its web banking site and a nightly reconciliation job all call the Account Information API. If the API trusts "any valid token from our identity provider", a token issued to the marketing microsite (which only needed to show a name) could read balances. If the reconciliation job uses a customer's credentials, an auditor cannot tell people from machines. A correctly designed user pool gives every caller its own app client, every API its own resource server, and every permission its own scope, so the API can reject tokens that were never meant for it.

The idea in plain language

A user pool is a managed user directory plus an OAuth 2.0 / OpenID Connect authorization server. It stores customers, signs them in (password, passkey, MFA, social or SAML federation) and issues three JWTs: an ID token (who the user is, for the app), an access token (what the caller may do, for the API) and a refresh token (to get new ones).

Inside the pool you register:

  • App clients: one per application that requests tokens. A browser or mobile app is a public client (no secret, uses PKCE). A server job is a confidential client (has a secret, can use client credentials).
  • Resource servers: one per API, with an identifier such as harbourline-accounts and custom scopes such as accounts.read. Tokens carry them as harbourline-accounts/accounts.read.

Analogy: The user pool is the bank's ID office. App clients are the registered counters that may ask for passes. A resource server is a building, and scopes are the doors inside it. The pass (access token) lists which doors it opens, and the guard at each door (your API) checks the pass is genuine, current and lists that door.

An identity pool is a different thing: it swaps a token (from a user pool, Google, SAML…) for temporary AWS credentials so an app can call AWS services such as S3 directly. This lesson does not need one.

What problem the AWS service solves

Cognito removes the need to run your own identity server (IdentityServer/Duende, Keycloak) for customer identities: storage, password hashing, MFA, account recovery, token signing and key rotation are managed.

Feature plans (checked on the Cognito pricing page and feature plans page, us-east-1, 2026-11-17):

PlanWhat it addsPrice per MAUFree tier
LiteSign-up/sign-in, groups, federation, OAuth 2.0 server, M2M, resource servers, SMS/TOTP MFA, classic hosted UI, ID-token customisationTiered, from USD 0.005510,000 MAU per account/organisation
Essentials (default for new pools)Everything in Lite plus managed login, passkeys, passwordless, email MFA, access-token customisation (pre token generation V2/V3), session managementUSD 0.01510,000 MAU per account/organisation
PlusEverything in Essentials plus threat protection (adaptive authentication, compromised-credential detection, user activity logs and export) — the features formerly sold as "advanced security features"USD 0.020None

Other prices that matter:

  • Machine-to-machine (client credentials): USD 0.00225 per successful token request in us-east-1, no free tier; registered app clients are not charged extra.
  • SAML/OIDC federated users: USD 0.015 per MAU above 50 free.
  • The Cognito free tier does not expire after 12 months.

Sharp edges:

  • Scopes depend on how you sign in. Tokens from the SDK sign-in APIs (InitiateAuth, AdminInitiateAuth) only ever contain the scope aws.cognito.signin.user.admin. To get harbourline-accounts/accounts.read you must use the OAuth endpoints (/oauth2/authorize + /oauth2/token), the client-credentials grant, or add scopes with a pre token generation trigger (Essentials or Plus).
  • No aud in access tokens by default. The app client ID is in client_id. Cognito only sets aud when the client requests resource binding (RFC 8707 resource parameter) through managed login.
  • ID and access tokens are signed with different keys (kid differs). Validate each independently.
  • Managed login cookies last one hour, so setting access tokens shorter than an hour does not force re-authentication in the browser.
  • A resource server can hold at most 100 scopes.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Entra ID tenant / External ID tenantUser poolOne pool per customer population; no directory of employees
App registrationApp clientPublic vs confidential is decided by whether a secret exists
"Expose an API" + scopes (api://…/Accounts.Read)Resource server + custom scopes (harbourline-accounts/accounts.read)Cognito scope prefix is the resource server identifier
Access token aud = API client ID (v2)No aud; check client_id + scopeYour API must allow-list client IDs itself
scp claimscope claim (space-separated)Same idea, different name
App roles (roles claim) for daemonsScopes on a confidential client; groups (cognito:groups) for usersCognito M2M tokens carry scopes, not roles
Azure AD B2C user flowsManaged login (Essentials+) or classic hosted UIB2C is no longer sold to new customers (since 2025-05-01); Microsoft points to Entra External ID
Conditional Access risk policiesPlus plan threat protectionPer-pool, priced per MAU

Architecture

Security-boundary view: the user pool is the only component that holds passwords and private signing keys. The API only ever sees signed tokens and public keys. Each app client is a separate trust decision: the API's allow-list of client_id values is your equivalent of "which app registrations may call me".

Step-by-step implementation

Design the scopes before you click anything

Write down: one resource server per API (harbourline-accounts), scopes named after actions (accounts.read, statements.write), one app client per application, and which client may ask for which scope. The web client gets both scopes; the reconciliation job only accounts.read.

Create the pool, domain, resource server and clients

Use the CLI section below (or the CDK stack). The pool uses Essentials, admin-only user creation (banks do not allow open self-registration) and optional TOTP MFA.

Get tokens two ways and compare them

First the learning shortcut (USER_PASSWORD_AUTH), then the production flow (authorization code + PKCE through managed login). Decode both: only the second contains the custom scopes.

Point the API at the pool

Set the lab API's issuer, client allow-list and scope policies, then call it with each token.

AWS Console instructions

  1. Console → Amazon Cognito → User pools → Create user pool. Choose Traditional web application or Single-page application (SPA), sign-in identifier Email, disable self-registration, and name the app client hl-m04-web. The console creates a domain and a managed login style for you.
  2. Settings → Feature plans shows the current plan (Essentials by default).
  3. Branding → Domain → Resource servers → Create a resource server: identifier harbourline-accounts, scopes accounts.read and statements.write.
  4. Applications → App clients → hl-m04-web → Login pages → Edit: add the custom scopes, callback URL http://localhost:5173/callback, grant type Authorization code grant.
  5. Users → Create user with a fictional address such as amelia.hughes@example.com.
  6. User pool overview → Tags: add Project=cea-lab, Lab=m04-cognito, Environment=learn, Owner=<your-name>.

AWS CLI

# Run in Git Bash. Replace <your-name>; the domain prefix must be globally unique.
export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
SUFFIX=$RANDOM
DOMAIN_PREFIX="hl-m04-accounts-$SUFFIX"
CALLBACK="http://localhost:5173/callback"

# 1. User pool: Essentials plan, email sign-in, admin-created users only, tags.
POOL_ID=$(aws cognito-idp create-user-pool \
  --pool-name hl-m04-customers \
  --user-pool-tier ESSENTIALS \
  --username-attributes email \
  --auto-verified-attributes email \
  --admin-create-user-config AllowAdminCreateUserOnly=true \
  --policies 'PasswordPolicy={MinimumLength=14,RequireUppercase=true,RequireLowercase=true,RequireNumbers=true,RequireSymbols=false}' \
  --deletion-protection INACTIVE \
  --user-pool-tags Project=cea-lab,Lab=m04-cognito,Environment=learn,Owner=<your-name> \
  --query UserPool.Id --output text)
echo "$POOL_ID"

# 2. Optional TOTP MFA (free; SMS MFA would add messaging charges).
aws cognito-idp set-user-pool-mfa-config --user-pool-id "$POOL_ID" \
  --software-token-mfa-configuration Enabled=true --mfa-configuration OPTIONAL

# 3. Prefix domain with managed login (version 2).
aws cognito-idp create-user-pool-domain --user-pool-id "$POOL_ID" \
  --domain "$DOMAIN_PREFIX" --managed-login-version 2
DOMAIN="$DOMAIN_PREFIX.auth.us-east-1.amazoncognito.com"

# 4. Resource server with two custom scopes.
aws cognito-idp create-resource-server --user-pool-id "$POOL_ID" \
  --identifier harbourline-accounts --name "Harbourline Accounts API" \
  --scopes ScopeName=accounts.read,ScopeDescription="Read own accounts" \
           ScopeName=statements.write,ScopeDescription="Request statements"

# 5. Public client: no secret, auth code + PKCE, short-lived tokens, rotation.
#    ALLOW_USER_PASSWORD_AUTH is ONLY for the learning shortcut in step 7.
WEB_CLIENT_ID=$(aws cognito-idp create-user-pool-client --user-pool-id "$POOL_ID" \
  --client-name hl-m04-web --no-generate-secret \
  --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_USER_SRP_AUTH \
  --allowed-o-auth-flows code --allowed-o-auth-flows-user-pool-client \
  --allowed-o-auth-scopes openid email harbourline-accounts/accounts.read harbourline-accounts/statements.write \
  --callback-urls "$CALLBACK" --supported-identity-providers COGNITO \
  --prevent-user-existence-errors ENABLED --enable-token-revocation \
  --access-token-validity 60 --id-token-validity 60 --refresh-token-validity 720 \
  --token-validity-units AccessToken=minutes,IdToken=minutes,RefreshToken=minutes \
  --refresh-token-rotation Feature=ENABLED,RetryGracePeriodSeconds=10 \
  --query UserPoolClient.ClientId --output text)

# 6. Managed login needs a branding style per client when created by API.
aws cognito-idp create-managed-login-branding --user-pool-id "$POOL_ID" \
  --client-id "$WEB_CLIENT_ID" --use-cognito-provided-values

# 7. Fictional test user with a permanent password (no email is sent).
aws cognito-idp admin-create-user --user-pool-id "$POOL_ID" \
  --username amelia.hughes@example.com --message-action SUPPRESS \
  --user-attributes Name=email,Value=amelia.hughes@example.com Name=email_verified,Value=true
aws cognito-idp admin-set-user-password --user-pool-id "$POOL_ID" \
  --username amelia.hughes@example.com --password 'Learn-Only-Passw0rd-2026' --permanent

⚠ Learning shortcut — not for production

USER_PASSWORD_AUTH sends the password to Cognito in the request body and lets any script holding the password get tokens. It is the Cognito equivalent of the OAuth password grant, which RFC 9700 forbids. Use it only to inspect tokens in a sandbox, then remove the flow from the client (update-user-pool-client without ALLOW_USER_PASSWORD_AUTH). Production apps use authorization code + PKCE through managed login, or SRP/passkeys in a native app.

# 8a. Learning shortcut: SDK sign-in. Note the scope you get back.
ACCESS=$(aws cognito-idp initiate-auth --client-id "$WEB_CLIENT_ID" \
  --auth-flow USER_PASSWORD_AUTH \
  --auth-parameters USERNAME=amelia.hughes@example.com,PASSWORD='Learn-Only-Passw0rd-2026' \
  --query AuthenticationResult.AccessToken --output text)
# Decode the payload (second segment) to read the claims.
cut -d. -f2 <<<"$ACCESS" | tr '_-' '/+' | base64 -d 2>/dev/null; echo
# -> "scope":"aws.cognito.signin.user.admin"  (no custom scopes!)

# 8b. Production-style: authorization code + PKCE (S256).
VERIFIER=$(openssl rand -base64 64 | tr -d '\n=+/' | cut -c1-64)
CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=\n')
STATE=$(openssl rand -hex 16)
echo "https://$DOMAIN/oauth2/authorize?response_type=code&client_id=$WEB_CLIENT_ID&redirect_uri=$CALLBACK&scope=openid%20harbourline-accounts%2Faccounts.read&code_challenge_method=S256&code_challenge=$CHALLENGE&state=$STATE"
# Open the URL, sign in as Amelia. The browser lands on localhost:5173/callback?code=...&state=...
# (the page will not load; that is fine). Check state matches, then copy the code:
CODE=<paste-code-here>
curl -s -X POST "https://$DOMAIN/oauth2/token" \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d "grant_type=authorization_code&client_id=$WEB_CLIENT_ID&code=$CODE&redirect_uri=$CALLBACK&code_verifier=$VERIFIER"
# -> access_token with "scope":"openid harbourline-accounts/accounts.read"

The base64 decode may print a warning or miss the last characters because JWTs use unpadded base64url; that is harmless for reading claims.

Machine-to-machine (optional, paid): a confidential client with client_credentials costs USD 0.00225 per token request. Ten requests cost about USD 0.02.

JOB_CLIENT=$(aws cognito-idp create-user-pool-client --user-pool-id "$POOL_ID" \
  --client-name hl-m04-recon-job --generate-secret \
  --allowed-o-auth-flows client_credentials --allowed-o-auth-flows-user-pool-client \
  --allowed-o-auth-scopes harbourline-accounts/accounts.read \
  --query 'UserPoolClient.[ClientId,ClientSecret]' --output text)
read JOB_ID JOB_SECRET <<<"$JOB_CLIENT"
curl -s -X POST "https://$DOMAIN/oauth2/token" -u "$JOB_ID:$JOB_SECRET" \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials&scope=harbourline-accounts/accounts.read'
# M2M token: sub == client_id, no username, no cognito:groups, no refresh token.

Infrastructure as Code

infra/cdk/Harbourline.AccountInformation.Infra/IdentityConstruct.cs
using Amazon.CDK;
using Amazon.CDK.AWS.Cognito;
using Constructs;

namespace Harbourline.AccountInformation.Infra;

public sealed class IdentityConstruct : Construct
{
    public UserPool Pool { get; }
    public UserPoolClient WebClient { get; }

    public IdentityConstruct(Construct scope, string id, string domainPrefix) : base(scope, id)
    {
        Pool = new UserPool(this, "CustomerPool", new UserPoolProps
        {
            UserPoolName = "hl-m04-customers",
            FeaturePlan = FeaturePlan.ESSENTIALS,
            SelfSignUpEnabled = false,
            SignInAliases = new SignInAliases { Email = true },
            Mfa = Mfa.OPTIONAL,
            MfaSecondFactor = new MfaSecondFactor { Otp = true, Sms = false },
            PasswordPolicy = new PasswordPolicy { MinLength = 14 },
            AccountRecovery = AccountRecovery.EMAIL_ONLY,
            DeletionProtection = false,            // true in production
            RemovalPolicy = RemovalPolicy.DESTROY, // RETAIN in production
        });

        var read = new ResourceServerScope(new ResourceServerScopeProps
            { ScopeName = "accounts.read", ScopeDescription = "Read own accounts" });
        var write = new ResourceServerScope(new ResourceServerScopeProps
            { ScopeName = "statements.write", ScopeDescription = "Request statements" });

        var accountsApi = Pool.AddResourceServer("AccountsApi", new UserPoolResourceServerOptions
        {
            Identifier = "harbourline-accounts",
            UserPoolResourceServerName = "Harbourline Accounts API",
            Scopes = [read, write],
        });

        WebClient = Pool.AddClient("WebClient", new UserPoolClientOptions
        {
            UserPoolClientName = "hl-m04-web",
            GenerateSecret = false,
            OAuth = new OAuthSettings
            {
                Flows = new OAuthFlows { AuthorizationCodeGrant = true },
                Scopes =
                [
                    OAuthScope.OPENID,
                    OAuthScope.ResourceServer(accountsApi, read),
                    OAuthScope.ResourceServer(accountsApi, write),
                ],
                CallbackUrls = ["http://localhost:5173/callback"],
            },
            PreventUserExistenceErrors = true,
            AccessTokenValidity = Duration.Minutes(60),
            IdTokenValidity = Duration.Minutes(60),
            RefreshTokenValidity = Duration.Hours(12),
            RefreshTokenRotationGracePeriod = Duration.Seconds(10),
        });

        Pool.AddDomain("Domain", new UserPoolDomainOptions
        {
            CognitoDomain = new CognitoDomainOptions { DomainPrefix = domainPrefix },
            ManagedLoginVersion = ManagedLoginVersion.NEWER_MANAGED_LOGIN,
        });

        _ = new CfnManagedLoginBranding(this, "WebBranding", new CfnManagedLoginBrandingProps
        {
            UserPoolId = Pool.UserPoolId,
            ClientId = WebClient.UserPoolClientId,
            UseCognitoProvidedValues = true,
        });
    }
}

The lab's AccountInformationStack then wires the pool into the REST API with new CognitoUserPoolsAuthorizer(...) and AuthorizationScopes = ["harbourline-accounts/accounts.read"] on each method. Tags come from Tags.Of(stack).Add(...) in the app.

Complete code

The lab API's production authentication mode, simplified from labs/m04-account-information-api/src/Harbourline.AccountInformation.Api/Auth/AuthenticationSetup.cs:

Auth/CognitoAuthentication.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

namespace Harbourline.AccountInformation.Api.Auth;

public sealed class CognitoOptions
{
    public const string SectionName = "Auth:Cognito";
    public string Region { get; init; } = "us-east-1";
    public string UserPoolId { get; init; } = "";
    public string[] AllowedClientIds { get; init; } = [];
    public string Issuer => $"https://cognito-idp.{Region}.amazonaws.com/{UserPoolId}";
}

public static class CognitoAuthentication
{
    public static AuthenticationBuilder AddCognitoAccessTokens(
        this AuthenticationBuilder auth, CognitoOptions cognito)
    {
        return auth.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
        {
            options.Authority = cognito.Issuer;
            options.MapInboundClaims = false;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = cognito.Issuer,
                ValidateAudience = false,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.FromSeconds(30),
                ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
                NameClaimType = "sub",
            };
            options.Events = new JwtBearerEvents
            {
                OnTokenValidated = context =>
                {
                    var tokenUse = context.Principal?.FindFirst("token_use")?.Value;
                    var clientId = context.Principal?.FindFirst("client_id")?.Value;

                    if (!string.Equals(tokenUse, "access", StringComparison.Ordinal))
                        context.Fail("Only access tokens are accepted.");
                    else if (clientId is null || !cognito.AllowedClientIds.Contains(clientId, StringComparer.Ordinal))
                        context.Fail("This app client may not call the API.");

                    return Task.CompletedTask;
                },
            };
        });
    }

    public static bool HasScope(this System.Security.Claims.ClaimsPrincipal user, string scope) =>
        (user.FindFirst("scope")?.Value ?? "")
            .Split(' ', StringSplitOptions.RemoveEmptyEntries)
            .Contains(scope, StringComparer.Ordinal);
}
Program.cs (excerpt)
using Harbourline.AccountInformation.Api.Auth;

var builder = WebApplication.CreateBuilder(args);
var cognito = builder.Configuration.GetSection(CognitoOptions.SectionName).Get<CognitoOptions>()
              ?? throw new InvalidOperationException("Auth:Cognito is not configured.");

builder.Services.AddAuthentication().AddCognitoAccessTokens(cognito);
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("accounts:read", p => p.RequireAssertion(c => c.User.HasScope("harbourline-accounts/accounts.read")))
    .AddPolicy("statements:write", p => p.RequireAssertion(c => c.User.HasScope("harbourline-accounts/statements.write")));

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/v1/whoami", (System.Security.Claims.ClaimsPrincipal user) =>
        Results.Ok(new { sub = user.Identity?.Name, scope = user.FindFirst("scope")?.Value }))
   .RequireAuthorization("accounts:read");
app.Run();
appsettings.Development.json (excerpt)
{
  "Auth": {
    "Mode": "Cognito",
    "Cognito": { "Region": "us-east-1", "UserPoolId": "us-east-1_XXXXXXXXX", "AllowedClientIds": [ "<web-client-id>" ] }
  }
}

Code explained line by line

  1. CognitoOptions.Issuer builds the original issuer URL https://cognito-idp.us-east-1.amazonaws.com/<poolId>. It must match the token's iss exactly. (Cognito also offers an "updated issuer" on issuer-cognito-idp.<region>.amazonaws.com; if you switch, change this value.)
  2. options.Authority = cognito.Issuer makes JwtBearer download <issuer>/.well-known/openid-configuration, find jwks_uri, cache the keys and refresh them when an unknown kid arrives.
  3. MapInboundClaims = false keeps claim names as issued (sub, scope, client_id) instead of mapping them to long SOAP-era URIs.
  4. ValidateAudience = false is deliberate: Cognito access tokens have no aud. The client_id allow-list in OnTokenValidated replaces it. If you adopt resource binding, switch to ValidAudience = "https://accounts.api.example.com".
  5. ValidAlgorithms = [RsaSha256] rejects none, HMAC and anything unexpected, even if a key were confused.
  6. ClockSkew = 30 s replaces the 5-minute default so expired tokens die close to their exp.
  7. token_use == "access" blocks ID tokens, which are signed by the same pool and would otherwise pass signature and issuer checks.
  8. The client_id allow-list blocks tokens issued to other apps in the same pool (the marketing microsite example).
  9. HasScope splits the space-separated scope claim; policies map scopes to endpoints (accounts:read, statements:write), matching the lab's ScopeRequirement.
  10. Ownership (a customer sees only their accounts) is not done here: the lab maps sub to customer_id through ICustomerDirectory and filters in IAccountStore.

Security considerations

⚠ Learning shortcut — not for production

The lab pool has deletion protection off, RemovalPolicy.DESTROY, a password typed on the command line and a localhost callback. In production: deletion protection on, retain the pool, create users through your onboarding/KYC system, store secrets of confidential clients in AWS Secrets Manager, and register only HTTPS callback URLs.

  • Customer data is personal data. A user pool stores emails and phone numbers of real customers: decide the Region with your data-protection officer (UK GDPR data-transfer rules), document retention, and have security review the MFA and recovery design. This lesson does not make anything compliant.
  • Prefer passkeys or TOTP over SMS for MFA; SMS is phishable and costs money per message.
  • Plus plan threat protection (adaptive authentication, compromised-credential checks) is worth evaluating for retail banking sign-in, but it costs USD 0.020 per MAU with no free tier.
  • Revocation: keep token revocation enabled; AdminUserGlobalSignOut and /oauth2/revoke invalidate refresh tokens and the access tokens issued from them (Cognito checks origin_jti), but only for APIs that call Cognito, not for offline JWT validation, so keep access tokens short.
  • Lambda triggers (pre token generation V2_0/V3_0) can add or remove scopes. Treat the trigger code as part of your authorisation system: least-privilege role, code review, tests.

Banking use case

Harbourline creates one Essentials pool for UK retail customers. The web and mobile apps are public clients with PKCE; both request harbourline-accounts/accounts.read, and only the web app may request statements.write. The reconciliation job is a confidential client limited to accounts.read, with its secret in Secrets Manager. Customer CUS-00012345 (Amelia Hughes, amelia.hughes@example.com) signs in with a passkey; the API maps her sub to CUS-00012345 and returns only ACC-0000012345-style accounts she owns.

Common mistakes

  • Expecting custom scopes from InitiateAuth → SDK sign-in only grants aws.cognito.signin.user.admin → use the OAuth endpoints or a V2 pre token generation trigger.
  • Validating aud on Cognito access tokens → every token fails → validate client_id instead (or use resource binding).
  • Accepting ID tokens at the API → a REST API Cognito authorizer with no scopes configured accepts ID tokens → always configure authorization scopes, and check token_use in code.
  • One app client for everything → you cannot tell callers apart or revoke one → one client per application.
  • Hard-coding the JWKS keys → Cognito can add keys at any time → always fetch and cache from jwks_uri.

Troubleshooting

SymptomLikely causeFix
invalid_scope from /oauth2/authorizeScope not allowed on the app clientAdd it with update-user-pool-client --allowed-o-auth-scopes (repeat all settings: missing ones reset to defaults)
redirect_mismatchredirect_uri differs from the registered callback (trailing slash, port)Use the exact same string
Managed login page shows an error about styleClient created by API without brandingcreate-managed-login-branding --use-cognito-provided-values
API returns 401, logs say IDX10205/issuer invalidWrong Region or pool ID, or updated vs original issuerCompare token iss with ValidIssuer character by character
API returns 403Token valid but missing scopeRequest the scope at sign-in; check the policy name
NotAuthorizedException: USER_PASSWORD_AUTH flow not enabledFlow missing on clientAdd ALLOW_USER_PASSWORD_AUTH (sandbox only)
InvalidParameterException on update-user-pool-clientYou omitted settings and they resetUse describe-user-pool-client output as the base

Cost and cleanup

Cost: free for user sign-ins (Essentials, under 10,000 MAU per account). The optional client-credentials exercise costs USD 0.00225 per token request. TOTP MFA is free; do not enable SMS.

# Delete the domain first, then the pool (removes clients, resource servers, users).
aws cognito-idp delete-user-pool-domain --user-pool-id "$POOL_ID" --domain "$DOMAIN_PREFIX"
aws cognito-idp delete-user-pool --user-pool-id "$POOL_ID"
# CDK path instead: cdk destroy
# Final check: nothing tagged Project=cea-lab remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --profile learn-sandbox

Exercises

  • 🟢 Guided: Run the CLI walkthrough, decode both access tokens and list three claims that differ between the initiate-auth token and the PKCE token.
  • 🟡 Challenge: Create a second public client hl-m04-marketing with only openid email. Get a token for it and prove the lab API returns 401 (client not allow-listed), then add it to the allow-list and prove it returns 403 (scope missing).
  • 🔴 Live problem: A ticket says "since yesterday the mobile app gets 401 from the Accounts API after exactly one hour, but the web app is fine". Both use the same pool. Investigate and propose a fix.

Assignment

Add an IdentityConstruct like the one above to your portfolio repository, with a second confidential client for a "statement generator" service limited to statements.write. Include a README table of clients, grants, scopes and token lifetimes, and justify each lifetime.

Solutions

Knowledge check

Interview questions

  • How would you model three apps and two APIs in Cognito? One user pool for the customer population, one app client per app (public with PKCE or confidential), one resource server per API with action-named scopes, and each client allowed only the scopes it needs.
  • What does Cognito's access token lack compared with Entra ID's, and how do you compensate? No aud by default; validate iss, token_use, client_id allow-list and scopes, or use resource binding for an aud.
  • How do you authenticate a batch job? Confidential client with client credentials (or GetClientToken), secret in Secrets Manager, narrow scopes, token cached until near expiry because each token request is billed.
  • When would you pay for the Plus plan? When you need adaptive, risk-based authentication and compromised-credential detection on customer sign-in and the per-MAU cost is justified by fraud risk.
  • How does refresh token rotation change client code? The client must store the new refresh token after each refresh, and cannot use REFRESH_TOKEN_AUTH; use GetTokensFromRefreshToken or the token endpoint.

Certification practice

Completion checklist

  • I can explain user pool vs identity pool and the three feature plans
  • I created a pool, resource server and two app clients, and got a PKCE token with a custom scope
  • I configured JwtBearer with issuer, token_use and client_id checks
  • I deleted the pool and confirmed nothing tagged Project=cea-lab remains

Key takeaways

  • One pool per user population, one app client per application, one resource server per API, scopes named after actions.
  • Custom scopes come only from the OAuth endpoints (or a V2/V3 trigger), never from SDK sign-in.
  • Cognito access tokens have client_id, scope and token_use, but no aud unless you use resource binding.
  • Essentials is the default plan and is free up to 10,000 MAU; M2M token requests are billed from the first one.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page