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

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.

intermediateโฑ 1 h 15 min๐ŸŸข FreeDVA-C03SCS-C03SAA-C03

Assumes: .NET 10 LTS ยท Microsoft.IdentityModel.JsonWebTokens 8.x ยท Microsoft.AspNetCore.Authentication.JwtBearer 10.0.15 ยท Amazon Cognito user pools ยท Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Explain the roles in OAuth 2.0 (resource owner, client, authorization server, resource server) and map them onto a Harbourline mobile app, Amazon Cognito and the Account Information API.
  • Choose the right grant: authorization code with PKCE for people, client credentials for machines, and say why the implicit and password grants are no longer acceptable.
  • Tell an ID token from an access token and explain why your API must accept only access tokens.
  • Read a JWT (header, payload, signature), find the signing key in a JWKS, and list every check a resource server must make.
  • Validate tokens in ASP.NET Core with JwtBearer and in plain C# with JsonWebTokenHandler, and prove the failure cases with tests.

Prerequisites

Why this matters in banking

Picture a mobile banking API that returns account data for whatever customer number is in the URL, as long as the request carries a valid token. The token is fine; the API simply never asks whose token it is. Variations of this pattern appear again and again in public API breach write-ups and in the OWASP API Security Top 10: APIs that accept ID tokens meant for a web front end, accept tokens signed with alg: none, or trust a role claim that the client can influence. None of these failures needed a cryptographic break. They came from developers who used the libraries without knowing which questions the libraries answer and which they leave to you.

Harbourline's Account Information API will hold balances and transaction histories, which are personal data under UK GDPR and highly attractive to fraudsters. Before you configure Cognito (next lesson) you need a precise mental model of what a token proves.

The idea in plain language

OAuth 2.0 (RFC 6749) is a protocol for delegated authorisation. A customer (the resource owner) lets an app (the client) call an API (the resource server) on their behalf, without giving the app their password. A trusted authorization server checks who the customer is, asks for consent if needed, and hands the app an access token โ€” a short-lived credential that says "this client may do these things (scopes) for this user until this time".

OpenID Connect (OIDC) is a thin identity layer on top of OAuth 2.0. OAuth alone tells the API what the client may do; it doesn't tell the client who logged in. OIDC adds an ID token for the client, a standard openid scope, a UserInfo endpoint and a discovery document at /.well-known/openid-configuration.

A JSON Web Token (JWT), RFC 7519, is the most common token format. It is three base64url parts joined by dots: a header (which algorithm and key), a payload of claims (who, for whom, until when, what scopes), and a signature. Anyone can read a JWT; only the issuer can create a valid signature. A JWT is signed, not encrypted.

Analogy: a JWT access token is like a visitor badge at a bank's head office. Reception (the authorization server) checks your passport once and prints a badge with your name, the floors you may visit and an expiry time, plus a hologram that only reception can make. Every door reader (the API) checks the hologram, the expiry and the floor list. It doesn't phone reception for every door. The badge proves which floors; it doesn't prove you may open someone else's safe deposit box on that floor. That last check is the API's business logic.

What problem the AWS service solves

On AWS the authorization server is usually Amazon Cognito user pools (or an external IdP such as Entra ID, Okta or Ping that Cognito federates with). Cognito:

  • hosts the sign-in UI and the OAuth 2.0 endpoints (/oauth2/authorize, /oauth2/token, /oauth2/revoke, /oauth2/userInfo);
  • issues RS256-signed ID, access and refresh tokens;
  • publishes its public keys at https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json;
  • supports resource servers with custom scopes such as harbourline-accounts/accounts.read.

API Gateway can validate those tokens before your code runs: REST APIs with a Cognito user pool authorizer, HTTP APIs with a JWT authorizer, or either with a Lambda authorizer (lesson). Your ASP.NET Core code should validate again (defence in depth) and must always do the object-level check: does this customer own this account?

Limitations to know. Cognito access tokens have no aud claim; they carry client_id instead, so generic "validate the audience" advice doesn't fit as-is. Cognito does not issue opaque (reference) tokens, so there is no introspection endpoint; revocation stops refresh tokens from being used, but already-issued access tokens stay valid until they expire. Keep access tokens short-lived.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Microsoft Entra ID / Azure AD B2CAmazon Cognito user poolsCognito is regional; B2C-style user flows are hosted UI or Managed Login
App registration + "Expose an API" scopesUser pool app client + resource server with custom scopesScope names are resourceServerId/scope, e.g. harbourline-accounts/accounts.read
aud = Application ID URIAccess token has no aud; check client_idValidate client_id against an allow-list instead
scp (delegated) and roles (app) claimsscope claim (space-separated); cognito:groupsOne scope claim for both user and client-credentials tokens
MSAL.js / MSAL.NETAmplify libraries, or any certified OIDC client libraryUse a standards library; avoid hand-rolled OAuth
AddMicrosoftIdentityWebApiAddJwtBearer with Authority = user pool issuerSame JwtBearer handler underneath
Managed identity for service-to-serviceIAM roles + SigV4, or Cognito client credentialsAWS-to-AWS calls normally use IAM, not OAuth (IAM/SigV4 and mTLS)

Architecture

Trust boundaries. The app runs on a phone you don't control, so it is a public client: it cannot keep a secret. PKCE proves that the party redeeming the code is the one that started the flow. The API trusts only the authorization server's signing keys, never anything the app asserts directly.

Step-by-step implementation

Pick the grant for each caller

CallerGrantWhy
Mobile app, SPA, desktop app (a person is present)Authorization code + PKCE (RFC 7636)Code is useless without the verifier; no secret on the device
Server-side web app (a person is present)Authorization code + PKCE, with a client secretConfidential client; PKCE still recommended
Batch job, partner system, internal service (no person)Client credentialsThe client is the principal; tokens have no sub for a person
Smart TV, kiosk without a keyboardDevice authorization grant (RFC 8628)Not supported by Cognito โš  VERIFY
Browser apps (legacy)ImplicitTokens in the URL fragment; forbidden by the OAuth 2.0 Security BCP
First-party "login form"Resource owner passwordApp sees the password; no MFA story; forbidden by the BCP

The OAuth 2.0 Security Best Current Practice (RFC 9700, January 2025) is the document to cite in design reviews: PKCE for all clients using the code flow, no implicit grant, no password grant, exact redirect URI matching, sender-constrained or short-lived tokens, refresh-token rotation for public clients.

Understand the three token types

TokenAudiencePurposeLifetime (Cognito default)Send to your API?
ID tokenThe client (aud = app client ID)Tells the app who signed in (email, name, auth_time)60 minutesNever
Access tokenThe resource serverGrants scopes to call APIs60 minutes (Harbourline sets 15)Yes, as Authorization: Bearer
Refresh tokenThe authorization server onlyGets new ID/access tokens without signing in again30 days (Harbourline sets 8 hours)Never

Cognito puts token_use in both JWTs (id or access). Checking it is how you stop the "ID token accepted as access token" bug: an ID token is signed by the same keys and has the same issuer, so signature and issuer checks alone would pass.

Read a JWT

A Cognito-shaped access token, decoded (all values fictional):

// Header
{ "kid": "abcdEXAMPLEkid=", "alg": "RS256" }

// Payload
{
  "sub": "8f2c1a7e-0b5d-4e3a-9c11-2d4e6f8a9b10",
  "iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE",
  "client_id": "4exampleclientid0000000000",
  "token_use": "access",
  "scope": "openid harbourline-accounts/accounts.read",
  "auth_time": 1763456400,
  "iat": 1763456400,
  "exp": 1763457300,
  "jti": "5b0c1e3d-7a2f-4c8e-9d1a-0f2e3d4c5b6a",
  "username": "8f2c1a7e-0b5d-4e3a-9c11-2d4e6f8a9b10"
}
  • iss โ€” who issued it. Must equal your user pool URL exactly.
  • sub โ€” stable, unique user identifier inside this pool. Use it as the key to your customer record. Never use email or username as a key: they can change or be reused.
  • exp, iat, nbf โ€” Unix seconds. Reject expired tokens; allow at most a small clock skew (30โ€“60 s).
  • client_id โ€” which app client obtained the token.
  • scope โ€” one space-separated string.
  • kid (header) โ€” which key in the JWKS signed it.

Find the key: discovery and JWKS

The resource server downloads {issuer}/.well-known/openid-configuration, reads jwks_uri, downloads the JSON Web Key Set and caches it. When a token arrives with an unknown kid, a good library refreshes the JWKS once (keys rotate) and then fails. JwtBearer does this for you when you set Authority. The keys are public; there is nothing secret to store.

Apply every validation rule

A resource server must check, in this order of cheapness:

  1. The header is Authorization: Bearer with three dot-separated parts (else 401).
  2. alg is one you expect โ€” RS256 for Cognito. Reject none, and never accept HMAC (HS256) when you expect RSA (the algorithm confusion attack).
  3. The signature verifies with a key from the issuer's JWKS, chosen by kid.
  4. iss equals your issuer exactly.
  5. exp is in the future, nbf (if present) in the past, with small skew.
  6. token_use is access.
  7. client_id is in your allow-list (for Cognito; with other IdPs, check aud).
  8. The required scope for this operation is present (else 403).
  9. Object-level: the resource belongs to the principal (else 404, see the REST design lesson).

Steps 1โ€“7 are authentication; API Gateway's Cognito or JWT authorizer can do them at the edge. Step 8 can be done at the edge too. Step 9 can only be done in your code.

Store tokens safely on the client

ClientRecommendation
Native mobile appPlatform secure storage (iOS Keychain, Android Keystore); system browser for sign-in (RFC 8252), never an embedded WebView
SPAPrefer a backend-for-frontend (BFF) that keeps tokens server-side and gives the browser an HttpOnly, Secure, SameSite session cookie. If tokens must live in the browser, keep them in memory, never localStorage
Server-side app or jobSecrets Manager for client secrets; tokens in memory only

AWS Console instructions

Nothing to create in this lesson. To see the concepts in a real user pool (if you already have one from the Cognito lesson): Console โ†’ Amazon Cognito โ†’ User pools โ†’ (pool) โ†’ Overview shows the Token signing key URL (the JWKS). App integration โ†’ App clients โ†’ (client) โ†’ Login pages shows allowed OAuth grant types and scopes. App integration โ†’ Resource servers shows custom scopes.

AWS CLI

Read-only commands against an existing pool; no AWS account changes.

# The discovery document and JWKS are public: no credentials needed.
curl -s https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE/.well-known/openid-configuration
curl -s https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE/.well-known/jwks.json

# Inspect an app client's token settings (validity, allowed flows and scopes).
aws cognito-idp describe-user-pool-client \
  --user-pool-id us-east-1_EXAMPLE --client-id 4exampleclientid0000000000 \
  --profile learn-sandbox --region us-east-1 \
  --query "UserPoolClient.{Access:AccessTokenValidity,Units:TokenValidityUnits,Flows:AllowedOAuthFlows,Scopes:AllowedOAuthScopes}"

To decode a token on Windows without pasting it into a website (tokens are credentials), use PowerShell:

# Decode the payload of a JWT locally. Never paste real tokens into online decoders.
$jwt = Get-Content .\token.txt -Raw
$part = $jwt.Split('.')[1].Replace('-', '+').Replace('_', '/')
switch ($part.Length % 4) { 2 { $part += '==' } 3 { $part += '=' } }
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($part)) | ConvertFrom-Json

Infrastructure as Code

The user pool, resource server and app client for this module are defined in the module project's CDK stack (labs/m04-account-information-api/infra/cdk/Harbourline.AccountInformation.Infra/AccountInformationStack.cs). The relevant OAuth settings, as a reminder of what each line means:

var webClient = pool.AddClient("WebClient", new UserPoolClientOptions
{
    GenerateSecret = false,                                   // public client: PKCE replaces the secret
    OAuth = new OAuthSettings
    {
        Flows = new OAuthFlows { AuthorizationCodeGrant = true }, // no implicit grant
        Scopes = [OAuthScope.OPENID, OAuthScope.ResourceServer(resourceServer, readScope)],
        CallbackUrls = ["http://localhost:5173/callback"],     // exact match, no wildcards
    },
    AccessTokenValidity = Duration.Minutes(15),
    RefreshTokenValidity = Duration.Hours(8),
    PreventUserExistenceErrors = true,
    EnableTokenRevocation = true,
});

Complete code

A console app that plays both roles locally: it creates an RSA key pair (the "authorization server"), publishes the public key as a JWKS, mints tokens, then validates them exactly as a resource server would โ€” including the attacks. Create it with dotnet new console -n Harbourline.TokenLab, add the package, and replace Program.cs.

Harbourline.TokenLab.csproj (excerpt)
<ItemGroup>
  <PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.*" />
</ItemGroup>
Program.cs
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

const string Issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE";
const string ClientId = "4exampleclientid0000000000";
const string RequiredScope = "harbourline-accounts/accounts.read";

// ---- "Authorization server": a private signing key that never leaves it ----
using var rsa = RSA.Create(2048);
var signingKey = new RsaSecurityKey(rsa) { KeyId = "key-2026-11" };
var signing = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256);

// ---- What it publishes: the JWKS (public parts only) ----
var publicJwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(
    new RsaSecurityKey(rsa.ExportParameters(includePrivateParameters: false)) { KeyId = "key-2026-11" });
var jwksJson = JsonSerializer.Serialize(new { keys = new[] { publicJwk } });
Console.WriteLine($"JWKS published by the issuer ({jwksJson.Length} bytes, public key only)\n");

string Mint(string tokenUse = "access", string clientId = ClientId, string scope = RequiredScope,
            string issuer = Issuer, int minutes = 15, SigningCredentials? creds = null)
{
    var now = DateTime.UtcNow;
    return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
    {
        Issuer = issuer,
        IssuedAt = now,
        NotBefore = now.AddMinutes(Math.Min(0, minutes) - 1),
        Expires = now.AddMinutes(minutes),
        SigningCredentials = creds ?? signing,
        Claims = new Dictionary<string, object>
        {
            ["sub"] = "8f2c1a7e-0b5d-4e3a-9c11-2d4e6f8a9b10",
            ["client_id"] = clientId,
            ["token_use"] = tokenUse,
            ["scope"] = scope,
            ["jti"] = Guid.NewGuid().ToString(),
        },
    });
}

// ---- "Resource server": trusts only keys from the JWKS ----
var jwks = new JsonWebKeySet(jwksJson);
var parameters = new TokenValidationParameters
{
    ValidIssuer = Issuer,
    ValidateAudience = false,                      // Cognito access tokens have no "aud"
    ValidateLifetime = true,
    ClockSkew = TimeSpan.FromSeconds(30),
    IssuerSigningKeys = jwks.GetSigningKeys(),
    ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
};

async Task<string> CheckAsync(string token)
{
    var result = await new JsonWebTokenHandler().ValidateTokenAsync(token, parameters);
    if (!result.IsValid)
        return $"401  {result.Exception?.GetType().Name}";

    var claims = result.ClaimsIdentity;
    if (claims.FindFirst("token_use")?.Value != "access")
        return "401  not an access token";
    if (claims.FindFirst("client_id")?.Value != ClientId)
        return "401  client not allowed";

    var scopes = (claims.FindFirst("scope")?.Value ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries);
    return scopes.Contains(RequiredScope) ? $"200  sub={claims.FindFirst("sub")?.Value}" : "403  missing scope";
}

// An attacker's own key, and an HMAC key built from the *public* RSA modulus (algorithm confusion).
using var attackerRsa = RSA.Create(2048);
var attackerCreds = new SigningCredentials(new RsaSecurityKey(attackerRsa) { KeyId = "key-2026-11" }, SecurityAlgorithms.RsaSha256);
var confusionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(publicJwk.N)) { KeyId = "key-2026-11" };
var confusionCreds = new SigningCredentials(confusionKey, SecurityAlgorithms.HmacSha256);

var good = Mint();
var tampered = TamperPayload(good);

var cases = new (string Name, string Token)[]
{
    ("valid access token", good),
    ("ID token instead of access token", Mint(tokenUse: "id")),
    ("token for another app client", Mint(clientId: "someotherclient00000000000")),
    ("token from another issuer", Mint(issuer: "https://evil.example")),
    ("expired token", Mint(minutes: -10)),
    ("read scope missing", Mint(scope: "openid")),
    ("signed by attacker's key", Mint(creds: attackerCreds)),
    ("HS256 with public key as secret", Mint(creds: confusionCreds)),
    ("payload edited after signing", tampered),
    ("alg none, no signature", UnsignedToken()),
};

foreach (var (name, token) in cases)
    Console.WriteLine($"{await CheckAsync(token),-45} {name}");

// Change "scope" in the payload without re-signing.
static string TamperPayload(string jwt)
{
    var parts = jwt.Split('.');
    var json = Encoding.UTF8.GetString(Base64UrlEncoder.DecodeBytes(parts[1]))
        .Replace("accounts.read", "accounts.admin", StringComparison.Ordinal);
    return $"{parts[0]}.{Base64UrlEncoder.Encode(json)}.{parts[2]}";
}

// A token that claims "no algorithm" โ€” must always be rejected.
static string UnsignedToken()
{
    var header = Base64UrlEncoder.Encode("""{"alg":"none","typ":"JWT"}""");
    var payload = Base64UrlEncoder.Encode(
        $$"""{"iss":"{{Issuer}}","sub":"x","token_use":"access","client_id":"{{ClientId}}","scope":"{{RequiredScope}}","exp":{{DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds()}}}""");
    return $"{header}.{payload}.";
}

Expected output (exception names can vary slightly between library versions):

JWKS published by the issuer (โ€ฆ bytes, public key only)

200  sub=8f2c1a7e-0b5d-4e3a-9c11-2d4e6f8a9b10      valid access token
401  not an access token                         ID token instead of access token
401  client not allowed                          token for another app client
401  SecurityTokenInvalidIssuerException         token from another issuer
401  SecurityTokenExpiredException               expired token
403  missing scope                               read scope missing
401  SecurityTokenSignatureKeyNotFoundException  signed by attacker's key
401  SecurityTokenInvalidAlgorithmException      HS256 with public key as secret
401  SecurityTokenInvalidSignatureException      payload edited after signing
401  SecurityTokenInvalidSignatureException      alg none, no signature

Code explained line by line

  1. RSA.Create(2048) โ€” the authorization server's key pair. Cognito does this for you and rotates keys; the private key never leaves AWS.
  2. JsonWebKeyConverter.ConvertFromRSASecurityKey(...) with includePrivateParameters: false โ€” builds the public JWK (kty, n, e, kid). This is what jwks.json contains.
  3. Mint(...) โ€” creates a JWT with Cognito-shaped claims. Parameters let us create bad tokens on purpose.
  4. new JsonWebKeySet(jwksJson) and GetSigningKeys() โ€” the resource server only knows the public keys, just as JwtBearer does after downloading the JWKS.
  5. ValidateAudience = false โ€” correct for Cognito access tokens only, because they carry client_id instead of aud. With Entra ID or Okta you validate aud.
  6. ValidAlgorithms = [RsaSha256] โ€” pins the algorithm. This defeats both alg: none and the HS256 confusion attack, even with older libraries.
  7. ClockSkew = 30 s โ€” the default in Microsoft.IdentityModel is 5 minutes, which is generous for 15-minute tokens.
  8. ValidateTokenAsync returns a TokenValidationResult instead of throwing; IsValid and Exception tell you why it failed.
  9. The token_use and client_id checks are the Cognito-specific rules that generic libraries don't know about.
  10. The scope check splits the space-separated scope claim. Missing scope is 403, not 401: the caller is authenticated, just not allowed.
  11. confusionKey โ€” the classic attack: sign with HMAC using the public key bytes as the "secret". A library that picks the algorithm from the token header would accept it.
  12. TamperPayload changes the payload without re-signing; the signature no longer matches.
  13. UnsignedToken โ€” alg: none with an empty signature. Modern libraries reject it by default; pinning ValidAlgorithms makes that explicit.

In ASP.NET Core the same rules become configuration (labs/m04-account-information-api/src/Harbourline.AccountInformation.Api/Auth/CognitoAuthentication.cs):

Auth/CognitoAuthentication.cs (excerpt)
options.Authority = cognito.Issuer;          // discovery + JWKS download and caching
options.MapInboundClaims = false;            // keep "sub" and "scope" as issued
options.TokenValidationParameters = new TokenValidationParameters
{
    ValidIssuer = cognito.Issuer,
    ValidateAudience = false,
    ValidateLifetime = true,
    ClockSkew = TimeSpan.FromSeconds(30),
    ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
    NameClaimType = "sub",
};
options.Events = AccessTokenChecks.Events(cognito.AllowedClientIds); // token_use + client_id

MapInboundClaims = false matters: by default the handler renames sub to a long WS-Federation URI, and code that looks for "sub" then finds nothing.

Security considerations

โš  Learning shortcut โ€” not for production

The console app holds the private signing key and the validator in the same process, and the module project's local mode signs test tokens with a shared HMAC key. Both exist so you can learn without an AWS account. In production the authorization server (Cognito) holds RS256 private keys that never leave it, and the API only ever sees the public JWKS. The module project refuses its local test issuer outside the Development environment.

  • Never log tokens. Log jti, sub and client_id if you need traceability. A logged bearer token is a usable credential until it expires.
  • Short access tokens, rotating refresh tokens. 5โ€“15 minutes for banking access tokens. Revocation in Cognito only stops refresh tokens; issued access tokens remain valid until exp.
  • Bearer means "whoever holds it". For high-risk APIs (payments, Open Banking), standards such as FAPI require sender-constrained tokens (mTLS-bound, RFC 8705, or DPoP, RFC 9449). Cognito does not issue sender-constrained tokens โš  VERIFY; see Open Banking / PSD2 in this module.
  • Claims are not permissions you invented. Don't put isAdmin in a token and trust it without knowing who can set it. Custom attributes in Cognito can be writable by the app client unless you restrict write permissions.
  • Consent and personal data. Scopes are part of what a customer consents to. The meaning of each scope and the data it exposes belong in your records of processing, reviewed with the data protection officer โ€” this lesson doesn't make anything UK GDPR compliant.

Banking use case

Harbourline has three kinds of callers for the Account Information API:

  1. Retail customers in the mobile app: authorization code + PKCE through Cognito's managed login, MFA required, 15-minute access tokens with accounts.read, 8-hour rotating refresh tokens.
  2. The statement-generation job (no person): a client-credentials token has no customer sub, so the API cannot map it to a customer, and a machine token that could act for any customer would be far too powerful. Harbourline gives machine callers separate, IAM-authorised internal routes instead (IAM/SigV4 and mTLS).
  3. Third-party providers under Open Banking: consent-bound tokens with FAPI profiles, out of scope for Cognito's defaults and covered later in the module.

Common mistakes

  • Accepting ID tokens at the API โ†’ they pass signature and issuer checks โ†’ check token_use (Cognito) or aud and typ (other IdPs).
  • Trusting the alg header โ†’ algorithm confusion โ†’ pin ValidAlgorithms.
  • Using email as the user key โ†’ emails change and can be recycled โ†’ key on sub.
  • Disabling lifetime validation "to fix a clock issue" โ†’ expired tokens accepted forever โ†’ fix NTP, keep skew small.
  • Treating 401 and 403 the same โ†’ clients retry sign-in when they should request a scope โ†’ 401 = who are you, 403 = not allowed.
  • Putting tokens in localStorage โ†’ any XSS steals them โ†’ BFF pattern or in-memory storage.
  • Assuming API Gateway validation is enough โ†’ anything that reaches your backend another way (a function URL, a misrouted ALB rule) bypasses it โ†’ validate in the app too.

Troubleshooting

SymptomLikely causeFix
IDX10500: Signature validation failed. No security keys were providedAuthority not set or metadata download blocked (no egress from private subnet)Set Authority; allow HTTPS egress to cognito-idp.us-east-1.amazonaws.com (NAT or proxy)
IDX10503/SecurityTokenSignatureKeyNotFoundException after a deploymentToken from a different pool (dev token on prod)Compare iss in the token with configuration
IDX10214: Audience validation failedValidating aud on a Cognito access tokenValidateAudience = false and check client_id
sub claim is null in codeInbound claim mapping renamed itMapInboundClaims = false
Always 403 although token looks rightScope check expects separate claims; Cognito sends one space-separated scopeSplit the claim value
SecurityTokenExpiredException with fresh tokensContainer clock drift or wrong time zone handlingUse UTC everywhere; check host time sync

Cost and cleanup

This lesson is free: the console app runs locally and creates no AWS resources. Nothing to clean up. (Cognito pricing for real sign-ins is covered in the Cognito lesson.)

Exercises

  • ๐ŸŸข Guided: Run the console app and confirm the ten results. Then change ClockSkew to five minutes and mint a token that expired three minutes ago. What happens, and why does it matter for a 15-minute token?
  • ๐ŸŸก Challenge: Add key rotation: create a second RSA key key-2026-12, publish both in the JWKS, sign new tokens with the new key, and show that tokens signed with either key validate. Then remove the old key and show which tokens now fail.
  • ๐Ÿ”ด Live problem: A ticket says: "Since Tuesday the mobile app shows 'session expired' every few minutes for some users in Germany; UK users are fine." Logs show SecurityTokenNotYetValidException on a subset of Fargate tasks. Write down your investigation and fix.

Assignment

Write a one-page token validation standard for Harbourline APIs: accepted algorithms, issuer allow-list, token_use/client_id rules, maximum lifetime and skew, logging rules, and the 401/403/404 decision table. Commit it to your portfolio repository with the console app.

Solutions

Knowledge check

Interview questions

  • "Explain OAuth 2.0 vs OpenID Connect in one minute." OAuth delegates authorisation: it gives a client an access token to call an API with certain scopes. OIDC adds authentication for the client: an ID token describing who signed in, a standard openid scope and discovery. APIs consume access tokens; apps consume ID tokens.
  • "How do you validate a JWT in .NET?" AddJwtBearer with Authority so keys come from the JWKS; validate issuer, lifetime with small skew, pin the algorithm, validate audience or the IdP's equivalent, then authorise by scope with policies and enforce object ownership in code.
  • "How would you revoke access immediately for a compromised customer?" Revoke refresh tokens and sign the user out globally in the IdP, keep access tokens short, and for instant effect add a deny-list check (by sub or jti) in the API or a Lambda authorizer for the remaining minutes.
  • "Why not use the password grant for our own app?" It exposes credentials to the app, blocks MFA and phishing-resistant methods, and is prohibited by the OAuth 2.0 Security BCP. Use authorization code + PKCE with the system browser.

Certification practice

Completion checklist

  • I can explain the four OAuth 2.0 roles using Harbourline's systems
  • I can say which grant fits a mobile app, a batch job and a partner system
  • I ran the console app and can explain every 401/403 result
  • I know why Cognito access tokens are checked with client_id instead of aud
  • No AWS resources were created (nothing to clean up)

Key takeaways

  • OAuth 2.0 gives access tokens to clients for APIs; OIDC adds ID tokens for clients. APIs accept only access tokens.
  • Use authorization code + PKCE for people and client credentials for machines; implicit and password grants are out (RFC 9700).
  • A JWT is signed, not encrypted. Validate signature (pinned algorithm, keys from JWKS), issuer, lifetime, token type and client, then scopes.
  • Token checks answer "who and which operations"; your code must still answer "which objects" (404 for others' data).

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