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.
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
audby default. - Configure ASP.NET Core
JwtBearerto accept only Cognito access tokens from allow-listed app clients.
Prerequisites
- Authentication fundamentals: OAuth 2.0, OIDC, JWT
- API Gateway REST vs HTTP vs WebSocket
- Tools: AWS CLI v2 with the
learn-sandboxSSO profile, Git Bash (foropensslandcurl), .NET 10 SDK, a browser
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-accountsand custom scopes such asaccounts.read. Tokens carry them asharbourline-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):
| Plan | What it adds | Price per MAU | Free tier |
|---|---|---|---|
| Lite | Sign-up/sign-in, groups, federation, OAuth 2.0 server, M2M, resource servers, SMS/TOTP MFA, classic hosted UI, ID-token customisation | Tiered, from USD 0.0055 | 10,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 management | USD 0.015 | 10,000 MAU per account/organisation |
| Plus | Everything 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.020 | None |
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 scopeaws.cognito.signin.user.admin. To getharbourline-accounts/accounts.readyou 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
audin access tokens by default. The app client ID is inclient_id. Cognito only setsaudwhen the client requests resource binding (RFC 8707resourceparameter) through managed login. - ID and access tokens are signed with different keys (
kiddiffers). 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 equivalent | What's different |
|---|---|---|
| Entra ID tenant / External ID tenant | User pool | One pool per customer population; no directory of employees |
| App registration | App client | Public 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 + scope | Your API must allow-list client IDs itself |
scp claim | scope claim (space-separated) | Same idea, different name |
App roles (roles claim) for daemons | Scopes on a confidential client; groups (cognito:groups) for users | Cognito M2M tokens carry scopes, not roles |
| Azure AD B2C user flows | Managed login (Essentials+) or classic hosted UI | B2C is no longer sold to new customers (since 2025-05-01); Microsoft points to Entra External ID |
| Conditional Access risk policies | Plus plan threat protection | Per-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
- 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. - Settings → Feature plans shows the current plan (Essentials by default).
- Branding → Domain → Resource servers → Create a resource server: identifier
harbourline-accounts, scopesaccounts.readandstatements.write. - Applications → App clients → hl-m04-web → Login pages → Edit: add the custom scopes, callback URL
http://localhost:5173/callback, grant type Authorization code grant. - Users → Create user with a fictional address such as
amelia.hughes@example.com. - 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
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:
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);
}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();{
"Auth": {
"Mode": "Cognito",
"Cognito": { "Region": "us-east-1", "UserPoolId": "us-east-1_XXXXXXXXX", "AllowedClientIds": [ "<web-client-id>" ] }
}
}Code explained line by line
CognitoOptions.Issuerbuilds the original issuer URLhttps://cognito-idp.us-east-1.amazonaws.com/<poolId>. It must match the token'sissexactly. (Cognito also offers an "updated issuer" onissuer-cognito-idp.<region>.amazonaws.com; if you switch, change this value.)options.Authority = cognito.Issuermakes JwtBearer download<issuer>/.well-known/openid-configuration, findjwks_uri, cache the keys and refresh them when an unknownkidarrives.MapInboundClaims = falsekeeps claim names as issued (sub,scope,client_id) instead of mapping them to long SOAP-era URIs.ValidateAudience = falseis deliberate: Cognito access tokens have noaud. Theclient_idallow-list inOnTokenValidatedreplaces it. If you adopt resource binding, switch toValidAudience = "https://accounts.api.example.com".ValidAlgorithms = [RsaSha256]rejectsnone, HMAC and anything unexpected, even if a key were confused.ClockSkew = 30 sreplaces the 5-minute default so expired tokens die close to theirexp.token_use == "access"blocks ID tokens, which are signed by the same pool and would otherwise pass signature and issuer checks.- The
client_idallow-list blocks tokens issued to other apps in the same pool (the marketing microsite example). HasScopesplits the space-separatedscopeclaim; policies map scopes to endpoints (accounts:read,statements:write), matching the lab'sScopeRequirement.- Ownership (a customer sees only their accounts) is not done here: the lab maps
subtocustomer_idthroughICustomerDirectoryand filters inIAccountStore.
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;
AdminUserGlobalSignOutand/oauth2/revokeinvalidate refresh tokens and the access tokens issued from them (Cognito checksorigin_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 grantsaws.cognito.signin.user.admin→ use the OAuth endpoints or a V2 pre token generation trigger. - Validating
audon Cognito access tokens → every token fails → validateclient_idinstead (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_usein 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
| Symptom | Likely cause | Fix |
|---|---|---|
invalid_scope from /oauth2/authorize | Scope not allowed on the app client | Add it with update-user-pool-client --allowed-o-auth-scopes (repeat all settings: missing ones reset to defaults) |
redirect_mismatch | redirect_uri differs from the registered callback (trailing slash, port) | Use the exact same string |
| Managed login page shows an error about style | Client created by API without branding | create-managed-login-branding --use-cognito-provided-values |
API returns 401, logs say IDX10205/issuer invalid | Wrong Region or pool ID, or updated vs original issuer | Compare token iss with ValidIssuer character by character |
| API returns 403 | Token valid but missing scope | Request the scope at sign-in; check the policy name |
NotAuthorizedException: USER_PASSWORD_AUTH flow not enabled | Flow missing on client | Add ALLOW_USER_PASSWORD_AUTH (sandbox only) |
InvalidParameterException on update-user-pool-client | You omitted settings and they reset | Use 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-sandboxExercises
- 🟢 Guided: Run the CLI walkthrough, decode both access tokens and list three claims that differ between the
initiate-authtoken and the PKCE token. - 🟡 Challenge: Create a second public client
hl-m04-marketingwith onlyopenid 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
The initiate-auth token has scope: aws.cognito.signin.user.admin and no custom scopes; the PKCE token has scope: openid harbourline-accounts/accounts.read. Both have token_use: access, the same client_id and sub, but different jti, iat/exp and possibly event_id. Why: SDK sign-in is designed for Cognito's own user APIs; OAuth scopes are only granted by the authorization server endpoints.
The marketing token passes signature, issuer and token_use checks but fails the client_id allow-list, so JwtBearer returns 401 (authentication failed). After allow-listing, authentication succeeds but the accounts:read policy fails, so ASP.NET Core returns 403. Why: 401 means "I do not accept who you are"; 403 means "I know who you are, but you may not do this".
Likely the mobile app does not refresh tokens, or uses REFRESH_TOKEN_AUTH on a client where refresh token rotation was just enabled (rotation is incompatible with that flow; use GetTokensFromRefreshToken or the /oauth2/token refresh_token grant). Check CloudTrail for UpdateUserPoolClient yesterday and the app's refresh error. Fix: switch the mobile app's refresh call, or temporarily disable rotation while the app is updated. The web app works because it refreshes through the token endpoint.
Knowledge check
Answer: A user pool authenticates users and issues JWTs for your apps and APIs. An identity pool exchanges a token for temporary AWS credentials so the app can call AWS services directly. An API that validates JWTs needs only a user pool.
Answer: Cognito access tokens carry the app client in client_id and have no aud unless resource binding was requested. Validate client_id against an allow-list instead.
Answer: Essentials or Plus (pre token generation event V2_0, or V3_0 to include M2M tokens). Lite can only customise ID tokens (V1_0), except legacy pools with advanced security features.
Answer: ID tokens from the same pool have a valid signature and issuer. Without token_use == "access", an app could call the API with an ID token, which is meant for the client, not the API.
Answer: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_AbC123/.well-known/jwks.json.
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
audby default; validateiss,token_use,client_idallow-list and scopes, or use resource binding for anaud. - 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; useGetTokensFromRefreshTokenor the token endpoint.
Certification practice
A developer signs users in from a .NET backend with AdminInitiateAuth and passes the access token to an API Gateway REST API whose Cognito authorizer requires the scope payments/transfer.create. Every call returns 401. What is the most likely fix?
A. Add payments/transfer.create to the app client's allowed OAuth scopes.
B. Sign users in through the /oauth2/authorize and /oauth2/token endpoints (authorization code + PKCE), requesting the scope.
C. Send the ID token instead of the access token.
D. Increase the access token validity.
Answer: B. SDK sign-in APIs only issue aws.cognito.signin.user.admin. A is necessary but not sufficient. C bypasses scopes and is insecure. D is unrelated.
A bank's nightly job must call an internal API protected by Cognito. No human is involved. The solution must avoid storing user passwords. Which design fits?
A. Create a test user for the job and use USER_PASSWORD_AUTH.
B. Create a confidential app client with a secret in Secrets Manager and use the client credentials grant with a narrow custom scope.
C. Use an identity pool to get IAM credentials and call the API with them.
D. Disable the authorizer for requests from the job's IP range.
Answer: B. Client credentials is the M2M grant. A puts a password in a job. C would require IAM authorisation on the API, which it does not use. D removes authentication.
An API validates Cognito JWT signatures and the issuer, then authorises by cognito:groups. A penetration tester calls the API with an ID token from a different app client in the same pool and succeeds. Which two controls fix this? (Choose two.)
A. Reject tokens whose token_use is not access.
B. Allow-list the expected client_id values.
C. Rotate the user pool signing keys.
D. Enable the Plus plan.
E. Move the API to a private REST API.
Answer: A and B. Rotation (C) does not change which tokens are accepted. Plus (D) protects sign-in, not token use. E changes network reachability, not token validation.
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_useandclient_idchecks - I deleted the pool and confirmed nothing tagged
Project=cea-labremains
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,scopeandtoken_use, but noaudunless 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
- User pool feature plans
- Amazon Cognito pricing
- Understanding the access token
- Scopes, M2M, and resource servers
- Pre token generation Lambda trigger
- Refresh tokens and rotation
- Identity provider and relying party endpoints
- Verifying JSON web tokens
- Configure JWT bearer authentication in ASP.NET Core
- Microsoft Entra External ID overview
- Next: Lambda authorizers · Exam prep: DVA-C03
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.
Authentication fundamentals: OAuth 2.0, OpenID Connect and JWTs
Understand OAuth 2.0 flows, OpenID Connect and JSON Web Tokens well enough to validate access tokens correctly in an ASP.NET Core API on AWS, and to spot the mistakes that leak banking data.
Lambda integrations for API Gateway
Connect .NET 10 Lambda functions to REST and HTTP APIs: proxy vs custom integrations, payload format 1.0 vs 2.0, ASP.NET Core on Lambda, error mapping, timeouts and cold starts, then build Lab 4.2 (HTTP API + Lambda + Cognito JWT authorizer with scopes).