Skip to Content
Cloud Engineering Academy
3. .NET Application Development on AWS

Authentication and authorisation for .NET APIs on AWS

Protect an ASP.NET Core API with Amazon Cognito access tokens, validate JWTs correctly (issuer, token_use, client_id, scopes), use policy-based authorisation, and keep user identity separate from the IAM role your code runs as.

intermediate⏱ 2 h 30 min🟡 Low costDVA-C03SCS-C03SAA-C03

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

Learning objectives

By the end of this lesson you can:

  • Distinguish the three identities in a running API: the end user (or calling system), the app client that obtained the token, and the IAM role your code uses to call AWS.
  • Set up an Amazon Cognito user pool with a resource server, custom scopes, a domain and an app client for the client credentials flow.
  • Explain the difference between Cognito ID tokens and access tokens, and why an API must accept only access tokens.
  • Configure JWT bearer validation in ASP.NET Core for Cognito: issuer, signature via JWKS, lifetime, token_use, client_id (Cognito access tokens have no aud), and scopes.
  • Write policy-based authorisation and test it without a real user pool by signing tokens locally.
  • Choose between validating JWTs in the app and with an API Gateway JWT authorizer, and give the running code least-privilege IAM roles for tasks, functions and instances.

Prerequisites

  • Module 3 overview and the Accounts API in labs/m03-accounts-api (this lesson explains its Security/AuthSetup.cs and its authentication tests)
  • Module 5: Security — IAM roles, policies and STS (recommended)
  • Logging and errors — 401/403 responses are ProblemDetails too
  • Tools: .NET 10 SDK or Docker; AWS CLI v2 with learn-sandbox; curl

Why this matters in banking

Harbourline's Accounts API returns balances and transactions. Under UK GDPR and the bank's own policies, only the right callers may see the right accounts, and every access must be attributable. Three real failure patterns:

  1. Accepting any valid-looking JWT. A developer validated the signature but not the issuer. A token from another Cognito user pool, created by an attacker in their own AWS account, was accepted because the API downloaded keys from whatever iss claimed. Lesson: pin the issuer.
  2. Accepting ID tokens as API credentials. ID tokens describe the user to the client app; they carry no scopes. Accepting them meant any front end that could sign a user in could call internal APIs. Lesson: require token_use = access and scopes.
  3. Confusing user identity with service identity. The API ran with an IAM role allowed to read every customer's data, and the code trusted a customerId query parameter. Any authenticated user could read anyone's accounts. Lesson: the IAM role says what the service may touch; the token says who is asking; your code must connect the two.

The idea in plain language

Authentication answers "who are you?". Authorisation answers "what may you do?".

In a modern API, the client does not send a password with each request. It first goes to an identity provider (Cognito, Entra ID, Okta), proves who it is, and receives a token: a signed JSON document (a JWT, JSON Web Token) saying who it is, who issued the token, until when it is valid and what it may do (scopes). The API checks the signature and the claims on every request. It never sees a password.

Scopes are named permissions such as harbourline-accounts/accounts.read. Policies in ASP.NET Core are rules like "authenticated, and has the accounts.read scope".

Separately, the API process itself has an IAM role: the permissions your code uses when it calls DynamoDB or Parameter Store. That is not the user's identity. It is the identity of the service.

Analogy: a bank visitor badge. Reception (Cognito) checks your ID and gives you a badge (the token) printed with your name, the issuing reception desk, an expiry time and the floors you may visit (scopes). Every door (the API) checks the badge is genuine, from this building's reception, not expired, and lists this floor. The building's own staff key (the IAM role) opens the vault for the cashier; it is never handed to visitors.

What problem Amazon Cognito solves

Amazon Cognito user pools are a managed OpenID Connect and OAuth 2.0 identity provider. They store users (or federate to a corporate IdP via SAML/OIDC), handle sign-in, MFA and password policies, and issue three JWTs: an ID token, an access token and a refresh token. For system-to-system calls they support the OAuth client credentials grant.

Building blocks for an API:

ConceptWhat it is
User poolThe directory and token issuer. Its issuer URL is https://cognito-idp.<region>.amazonaws.com/<pool-id>
App clientA registered application allowed to get tokens. A confidential client has a secret; a public client (mobile/SPA) does not
DomainHosts the OAuth endpoints (/oauth2/authorize, /oauth2/token) and managed login pages
Resource serverRepresents your API, with an identifier (harbourline-accounts) and custom scopes (accounts.read). Scopes appear as <identifier>/<scope>
JWKSThe public keys used to verify token signatures: <issuer>/.well-known/jwks.json

Honest limitations:

  • Cognito access tokens do not contain an aud (audience) claim; they contain client_id. Libraries that require an audience must be configured to check client_id instead (the lab does this).
  • Machine-to-machine (client credentials) token requests are billed per successful token response with no free tier. Cache tokens until shortly before expiry instead of requesting one per call.
  • Custom attributes, MFA options, advanced security and managed login styling depend on the feature plan (Lite, Essentials, Plus), which changes the price per monthly active user.
  • Cognito is not your authorisation engine. It says who the caller is and which scopes the client was granted; data-level rules ("this customer may see these accounts") live in your code or in Amazon Verified Permissions.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Microsoft Entra ID / Entra External ID (B2C)Amazon Cognito user poolsIssuer URL and claim names differ; access tokens have client_id, not aud
App registration "Expose an API" + scopesCognito resource server + custom scopesScope string is identifier/scope
App roles (roles claim)Cognito groups (cognito:groups claim)Groups appear in ID and access tokens
Client credentials with app secret or certificateCognito app client with secret, client credentials grantBilled per token request
AddMicrosoftIdentityWebApiAddJwtBearer with Authority = Cognito issuerNo AWS-specific middleware needed
APIM validate-jwt policyAPI Gateway JWT authorizer (HTTP APIs) or Cognito authorizer (REST APIs)Validation at the edge, before your code runs
Managed identity for the appIAM role for the ECS task / Lambda function / EC2 instance profileTemporary credentials delivered automatically to the SDK

Architecture

Security boundary view.

Two independent checks: the token (user/client identity, verified by the API or the edge) and the IAM role (service identity, verified by AWS on every SDK call). Neither replaces the other.

ID tokens versus access tokens

ID tokenAccess token
AudienceThe client app that signed the user in (aud = client id)The API (Cognito puts client_id, no aud)
PurposeTell the client who signed in (name, email)Authorise calls to resource servers
Contains scopesNoYes, in scope (space-separated)
token_use claimidaccess
Contains personal dataOften (email, name, custom attributes)Minimal (sub, username, groups)
Should your API accept it?NoYes

A decoded Cognito access token from the client credentials flow looks like this (fictional values):

{
  "sub": "4example0client0id0000000",
  "token_use": "access",
  "scope": "harbourline-accounts/accounts.read",
  "auth_time": 1795000000,
  "iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_AbCdEf123",
  "exp": 1795003600,
  "iat": 1795000000,
  "version": 2,
  "jti": "8d2b8f0e-0000-4000-8000-000000000000",
  "client_id": "4example0client0id0000000"
}

For client credentials, sub equals the client ID because the "user" is the client itself.

How the Accounts API validates tokens

Security/AuthSetup.cs from the lab, the core of it:

Security/AuthSetup.cs (excerpt)
services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(jwt =>
    {
        jwt.Authority = options.Authority;
        jwt.MapInboundClaims = false;
        jwt.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = options.Authority,
            ValidateAudience = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(1),
            NameClaimType = "sub",
        };
        jwt.Events = new JwtBearerEvents
        {
            OnTokenValidated = context =>
            {
                var principal = context.Principal!;
                if (principal.FindFirstValue("token_use") != "access")
                {
                    context.Fail("Only Cognito access tokens are accepted (token_use must be 'access').");
                }
                else if (!options.AllowedClientIds.Contains(principal.FindFirstValue("client_id")))
                {
                    context.Fail("The token was issued to an app client that may not call this API.");
                }
                return Task.CompletedTask;
            },
        };
    });

services.AddAuthorizationBuilder()
    .AddPolicy(AccountsReadPolicy, p => p
        .RequireAuthenticatedUser()
        .RequireAssertion(ctx => HasScope(ctx.User, options.RequiredScope)));

public static bool HasScope(ClaimsPrincipal user, string scope) =>
    user.FindAll("scope")
        .SelectMany(c => c.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
        .Contains(scope, StringComparer.Ordinal);

Line by line:

  1. AddAuthentication(JwtBearerDefaults.AuthenticationScheme) — the default scheme reads Authorization: Bearer ....
  2. jwt.Authority = options.Authority — the user pool issuer URL. The handler fetches {Authority}/.well-known/openid-configuration, finds jwks_uri, downloads the public keys and caches them, refreshing periodically and when an unknown key ID appears (so Cognito key rotation just works).
  3. MapInboundClaims = false — by default the handler renames claims to long WS-Federation URIs (sub becomes http://schemas.xmlsoap.org/...nameidentifier). Turning that off keeps Cognito's claim names, so FindFirstValue("client_id") works.
  4. ValidateIssuer = true, ValidIssuer = Authority — pins the issuer. A token signed by any other pool, even a genuine Cognito pool in another account, fails.
  5. ValidateAudience = false — necessary because Cognito access tokens have no aud. The audience check is replaced by the client_id check in step 8. Never turn off audience validation without that replacement.
  6. ValidateLifetime = true, ClockSkew = 1 minute — rejects expired tokens. The default skew is five minutes; one minute is enough for AWS hosts with synchronised clocks.
  7. token_use != "access" → context.Fail(...) — rejects ID tokens, which are signed by the same keys and would otherwise pass every other check.
  8. AllowedClientIds.Contains(client_id) — only app clients you registered may call the API. A token from the same pool but issued to, say, the marketing web app's client is rejected.
  9. AddPolicy(AccountsReadPolicy, ...) — the named policy accounts:read, applied to the whole /v1 route group with RequireAuthorization(AuthSetup.AccountsReadPolicy).
  10. HasScope — OAuth 2.0 puts all scopes into one space-separated scope claim. A naive HasClaim("scope", "harbourline-accounts/accounts.read") fails as soon as a token carries two scopes. The lab has a Theory test for exactly that.

Status codes. Missing, invalid, expired or wrong-issuer tokens produce 401 Unauthorized (authentication failed). A valid token without the scope produces 403 Forbidden (authenticated, not allowed). Health checks call .AllowAnonymous() so load balancers can reach them.

Safety catch. The lab supports Auth:Mode=Disabled for local work and throwaway deployments, but AddAccountsAuth throws at start-up if it is disabled outside Development unless Auth:AllowDisabledOutsideDevelopment=true is set explicitly. A forgotten setting therefore fails loudly instead of silently exposing data.

Testing authentication without Cognito

You do not need a real user pool to test all of this. The lab's CognitoAuthApiFactory (in tests/.../ApiFactories.cs) hosts the real Program with Auth:Mode=Cognito, then replaces the key download with a local signing key:

ApiFactories.cs (excerpt)
builder.ConfigureTestServices(services =>
    services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, o =>
    {
        o.ConfigurationManager = null;                       // no metadata download
        o.TokenValidationParameters.IssuerSigningKey = _key; // our local test key
    }));

CreateToken(...) signs tokens with that key and lets each test vary one claim. The AuthenticationTests class then proves the security properties as executable specifications:

TestExpected
No_token_is_401401
A_valid_access_token_with_the_scope_is_200200
A_valid_token_without_the_scope_is_403403
An_id_token_is_rejected401
A_token_for_another_app_client_is_rejected401
A_token_from_another_user_pool_is_rejected401
An_expired_token_is_rejected401
Health_checks_stay_anonymous_so_load_balancers_can_call_them200

When someone "simplifies" the validation later, one of these tests fails. That is how you keep security properties from eroding.

Data-level authorisation

Scopes say what kind of thing a client may do. They do not say whose data. For a customer-facing app, the access token's sub identifies the customer's Cognito user; you map it to a customer_id (for example via a custom claim added by a pre-token-generation Lambda trigger, or a lookup table) and then filter by it in code:

Resource-based check (sketch for a customer-facing endpoint)
v1.MapGet("/me/accounts", async (ClaimsPrincipal user, IAccountRepository repo, ICustomerDirectory directory, CancellationToken ct) =>
{
    var customerId = await directory.CustomerIdForSubjectAsync(user.FindFirstValue("sub")!, ct);
    return customerId is null
        ? Results.Problem(statusCode: 403, title: "No customer profile is linked to this sign-in.")
        : Results.Ok(await repo.GetAccountsForCustomerAsync(customerId, ct));
});

The customer never supplies the customer ID; it is derived from the verified token. That closes the "change the ID in the URL" class of bugs (OWASP API1, broken object level authorisation). The module project's /v1/customers/{customerId}/accounts endpoint is designed for trusted back-office systems using client credentials, which is why it is protected by scope only.

IAM roles for the running code

Your code calls AWS with the role of whatever runs it. The SDK finds these credentials automatically through the default credential chain; you never configure keys.

HostRoleTrusted principalNotes
ECS taskTask roleecs-tasks.amazonaws.comUsed by your app. Distinct from the task execution role, which ECS uses to pull images and write logs
LambdaExecution rolelambda.amazonaws.comUsed by your function code
EC2 / BeanstalkInstance profile wrapping a roleec2.amazonaws.comRetrieved through IMDSv2; disable IMDSv1

The module project grants every host the same read-only permissions through AccountsApiPermissions.GrantReadOnly: dynamodb:GetItem, Query and DescribeTable on one table and its indexes, and ssm:GetParametersByPath on one path. No writes, no other tables. Even if an attacker found a bug that let them run arbitrary queries, the role would limit the damage to read access on that table.

Validating at the edge: API Gateway JWT authorizers

For APIs fronted by API Gateway HTTP APIs, a JWT authorizer can validate Cognito tokens before Lambda or your container is invoked. You configure the issuer, the audience list (for Cognito access tokens, API Gateway matches the client_id claim against it) and, per route, required scopes.

Validate in ASP.NET CoreAPI Gateway JWT authorizer
Works on every host (Beanstalk, ECS, Lambda)YesOnly behind API Gateway
Rejects bad tokens before compute runs (cost, DoS)NoYes
Custom checks (token_use, data-level rules)YesIssuer, audience/client_id, expiry, scopes only
Testable in unit/integration testsYesOnly by deploying

Banks commonly do both: the edge filters obvious garbage cheaply, and the app enforces the full rules (defence in depth). The application must never assume the edge did its job.

Step-by-step implementation

Create the user pool, resource server and domain

A user pool for machine clients, a resource server harbourline-accounts with the scope accounts.read, and a domain for the token endpoint. Commands are in the CLI section.

Create a confidential app client for client credentials

Enable only the client_credentials flow and only the harbourline-accounts/accounts.read scope. Store the client secret in Secrets Manager, not in configuration files.

Configure the API

Set Auth__Mode=Cognito, Auth__Authority=https://cognito-idp.us-east-1.amazonaws.com/<pool-id> and Auth__AllowedClientIds__0=<client-id>. Run locally or redeploy one host.

Get a token and call the API

Request a token from /oauth2/token, call the API with it, then try the negative cases: no token (401), a token with a different scope (403).

Review the IAM side

Open the task role (or function role) and confirm it only grants what the code needs. Use IAM Access Analyzer's unused access findings later to trim it further.

AWS Console instructions

  • Amazon Cognito → User pools → Create user pool. For a machine-to-machine setup choose the Machine-to-machine application option when prompted for the application type, name it hl-m03-accounts-m2m. The wizard creates the pool, a domain and a confidential app client.
  • User pool → Branding → Domain shows the Cognito domain (https://<prefix>.auth.us-east-1.amazoncognito.com).
  • User pool → Branding → Domain → Resource servers → Create resource server — identifier harbourline-accounts, scope accounts.read.
  • User pool → Applications → App clients → your client → Login pages → Edit — under OAuth 2.0 grant types keep only Client credentials; under custom scopes tick harbourline-accounts/accounts.read.
  • User pool → Overview shows the User pool ID and the Token signing key URL (the JWKS).

Console layouts change; if a label differs, the concept (resource server, scopes, client credentials) is the same ⚠ VERIFY current console labels.

AWS CLI

export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
TAGS='Project=cea-lab,Lab=m03-auth,Environment=learn,Owner=<your-name>'

# 1. User pool (no self sign-up: machine clients only)
POOL_ID=$(aws cognito-idp create-user-pool --pool-name hl-m03-accounts-m2m \
  --admin-create-user-config AllowAdminCreateUserOnly=true \
  --user-pool-tags "$TAGS" --query UserPool.Id --output text)

# 2. Resource server = the API, with one custom scope
aws cognito-idp create-resource-server --user-pool-id "$POOL_ID" \
  --identifier harbourline-accounts --name "Harbourline Accounts API" \
  --scopes ScopeName=accounts.read,ScopeDescription="Read account information"

# 3. Domain prefix for the OAuth endpoints (must be globally unique)
aws cognito-idp create-user-pool-domain --user-pool-id "$POOL_ID" --domain hl-m03-<your-initials>-auth

# 4. Confidential app client for client credentials only
read CLIENT_ID CLIENT_SECRET < <(aws cognito-idp create-user-pool-client --user-pool-id "$POOL_ID" \
  --client-name hl-m03-backoffice --generate-secret \
  --allowed-o-auth-flows client_credentials --allowed-o-auth-flows-user-pool-client \
  --allowed-o-auth-scopes harbourline-accounts/accounts.read \
  --access-token-validity 60 --token-validity-units AccessToken=minutes \
  --query "UserPoolClient.[ClientId,ClientSecret]" --output text)

# 5. Get an access token (each successful response is billed; no free tier for M2M)
TOKEN=$(curl -s -X POST "https://hl-m03-<your-initials>-auth.auth.us-east-1.amazoncognito.com/oauth2/token" \
  -u "$CLIENT_ID:$CLIENT_SECRET" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&scope=harbourline-accounts/accounts.read" | python -c "import sys,json;print(json.load(sys.stdin)['access_token'])")

# 6. Run the API locally with Cognito validation on (from labs/m03-accounts-api)
Auth__Mode=Cognito \
Auth__Authority="https://cognito-idp.us-east-1.amazonaws.com/$POOL_ID" \
Auth__AllowedClientIds__0="$CLIENT_ID" \
dotnet run --project src/Harbourline.Accounts.Api --launch-profile http &

# 7. Positive and negative calls
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:5080/v1/accounts/ACC-0000000001   # 200
curl -i http://localhost:5080/v1/accounts/ACC-0000000001                                    # 401

The Development launch profile normally disables auth through appsettings.Development.json; environment variables win over that file, so the commands above turn validation on locally.

Infrastructure as Code

AuthStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.Cognito;
using Constructs;

namespace Harbourline.Accounts.Infra;

public sealed class AuthStack : Stack
{
    public AuthStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
    {
        var pool = new UserPool(this, "Pool", new UserPoolProps
        {
            UserPoolName = "hl-m03-accounts-m2m",
            SelfSignUpEnabled = false,
            DeletionProtection = false,               // ⚠ lab only; true in production
            RemovalPolicy = RemovalPolicy.DESTROY,
        });

        var readScope = new ResourceServerScope(new ResourceServerScopeProps
        {
            ScopeName = "accounts.read",
            ScopeDescription = "Read account information",
        });
        var api = pool.AddResourceServer("AccountsApi", new UserPoolResourceServerOptions
        {
            Identifier = "harbourline-accounts",
            Scopes = [readScope],
        });

        pool.AddDomain("Domain", new UserPoolDomainOptions
        {
            CognitoDomain = new CognitoDomainOptions { DomainPrefix = "hl-m03-learner-auth" },
        });

        var client = pool.AddClient("BackOffice", new UserPoolClientOptions
        {
            UserPoolClientName = "hl-m03-backoffice",
            GenerateSecret = true,
            AuthFlows = new AuthFlow(),                   // no user password flows
            AccessTokenValidity = Duration.Minutes(60),
            OAuth = new OAuthSettings
            {
                Flows = new OAuthFlows { ClientCredentials = true },
                Scopes = [OAuthScope.ResourceServer(api, readScope)],
            },
        });

        _ = new CfnOutput(this, "Authority", new CfnOutputProps { Value = pool.UserPoolProviderUrl });
        _ = new CfnOutput(this, "ClientId", new CfnOutputProps { Value = client.UserPoolClientId });
    }
}

Complete code

A token-caching client for the calling side (a back-office worker that calls the Accounts API). It fetches the client secret from Secrets Manager once, caches the access token until one minute before expiry, and attaches it to every request through a DelegatingHandler. Caching matters: every token response is billed, and the token endpoint has rate quotas.

Harbourline.BackOffice.Client.csproj
<Project Sdk="Microsoft.NET.Sdk.Worker">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SecretsManager" Version="4.1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="10.0.15" />
  </ItemGroup>
</Project>
Program.cs
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using Amazon.SecretsManager;
using Amazon.SecretsManager.Model;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddDefaultAWSOptions(builder.Configuration.GetAWSOptions());
builder.Services.AddAWSService<IAmazonSecretsManager>();

builder.Services.Configure<CognitoClientOptions>(builder.Configuration.GetSection("Cognito"));
builder.Services.AddHttpClient<CognitoTokenProvider>();
builder.Services.AddTransient<BearerTokenHandler>();
builder.Services.AddHttpClient("accounts", c =>
        c.BaseAddress = new Uri(builder.Configuration["AccountsApi:BaseUrl"] ?? "http://localhost:5080/"))
    .AddHttpMessageHandler<BearerTokenHandler>();
builder.Services.AddHostedService<NightlyCheck>();

await builder.Build().RunAsync();

public sealed class CognitoClientOptions
{
    public string TokenEndpoint { get; set; } = "";   // https://<prefix>.auth.us-east-1.amazoncognito.com/oauth2/token
    public string ClientId { get; set; } = "";
    public string ClientSecretId { get; set; } = "";  // Secrets Manager secret holding the client secret
    public string Scope { get; set; } = "harbourline-accounts/accounts.read";
}

/// <summary>Gets and caches client-credentials access tokens. Thread-safe; one token request at a time.</summary>
public sealed class CognitoTokenProvider(
    HttpClient http,
    IAmazonSecretsManager secrets,
    Microsoft.Extensions.Options.IOptions<CognitoClientOptions> options,
    TimeProvider clock)
{
    private readonly SemaphoreSlim _gate = new(1, 1);
    private string? _secret;
    private string? _token;
    private DateTimeOffset _expiresAt;

    public async Task<string> GetTokenAsync(CancellationToken ct)
    {
        if (_token is not null && clock.GetUtcNow() < _expiresAt) return _token;

        await _gate.WaitAsync(ct);
        try
        {
            if (_token is not null && clock.GetUtcNow() < _expiresAt) return _token; // another caller refreshed it
            var o = options.Value;
            _secret ??= (await secrets.GetSecretValueAsync(new GetSecretValueRequest { SecretId = o.ClientSecretId }, ct)).SecretString;

            using var request = new HttpRequestMessage(HttpMethod.Post, o.TokenEndpoint)
            {
                Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    ["grant_type"] = "client_credentials",
                    ["scope"] = o.Scope,
                }),
            };
            var basic = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{Uri.EscapeDataString(o.ClientId)}:{Uri.EscapeDataString(_secret)}"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", basic);

            using var response = await http.SendAsync(request, ct);
            response.EnsureSuccessStatusCode();
            var body = await JsonSerializer.DeserializeAsync<TokenResponse>(await response.Content.ReadAsStreamAsync(ct), cancellationToken: ct)
                ?? throw new InvalidOperationException("Empty token response.");

            _token = body.AccessToken;
            _expiresAt = clock.GetUtcNow().AddSeconds(body.ExpiresIn).AddMinutes(-1); // refresh a minute early
            return _token;
        }
        finally
        {
            _gate.Release();
        }
    }

    private sealed record TokenResponse(
        [property: JsonPropertyName("access_token")] string AccessToken,
        [property: JsonPropertyName("expires_in")] int ExpiresIn);
}

/// <summary>Adds "Authorization: Bearer ..." to every outgoing request of the named client.</summary>
public sealed class BearerTokenHandler(CognitoTokenProvider tokens) : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await tokens.GetTokenAsync(ct));
        return await base.SendAsync(request, ct);
    }
}

/// <summary>Example consumer: reads one account and logs its status (never the balance or IBAN).</summary>
public sealed class NightlyCheck(IHttpClientFactory factory, ILogger<NightlyCheck> log, IHostApplicationLifetime life) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var http = factory.CreateClient("accounts");
        using var response = await http.GetAsync("v1/accounts/ACC-0000000001", stoppingToken);
        log.LogInformation("Accounts API answered {StatusCode}", (int)response.StatusCode);
        life.StopApplication();
    }
}

Register TimeProvider.System with builder.Services.AddSingleton(TimeProvider.System); if your host template does not already (add it before Build()); in tests, inject a fake TimeProvider to prove the token is reused until one minute before expiry.

Code explained line by line

  1. AddAWSService<IAmazonSecretsManager>() — the client secret comes from Secrets Manager using the worker's own IAM role. The secret never sits in appsettings.json.
  2. AddHttpClient<CognitoTokenProvider>() — a typed client for the token endpoint; IHttpClientFactory manages its connections.
  3. AddHttpMessageHandler<BearerTokenHandler>() — every request through the accounts client gets a token automatically; callers never touch tokens.
  4. SemaphoreSlim _gate with double-checked _expiresAt — under load, only one request refreshes the token; others wait and reuse it. Without this, 50 concurrent requests at expiry would buy 50 tokens.
  5. FormUrlEncodedContent with grant_type=client_credentials and scope — the OAuth 2.0 token request. Requesting only the scope you need is least privilege for tokens.
  6. Basic authentication with URL-encoded id and secret — the client_secret_basic method that Cognito's token endpoint accepts for confidential clients.
  7. AddSeconds(ExpiresIn).AddMinutes(-1) — refresh before expiry so an in-flight request never carries a token that expires mid-call.
  8. NightlyCheck logs only the status code: tokens, secrets, balances and IBANs never go to logs.

Security considerations

⚠ Learning shortcut — not for production

The module project's deployed stacks run with Auth:Mode=Disabled and an explicit override, over plain HTTP, so you can measure the three hosts without setting up Cognito first. They serve fictional data and are destroyed within the hour. In production: Auth:Mode=Cognito with pinned issuer and allowed client IDs, HTTPS only (ACM certificate on the ALB or API Gateway's endpoint), AWS WAF in front, short access-token lifetimes, client secrets in Secrets Manager with rotation, and ideally a JWT authorizer at the edge as a second layer.

  • Never log tokens. A bearer token is a password for its lifetime. Exclude the Authorization header from request logging and from any HTTP client logging.
  • Prefer short lifetimes. Access tokens of 5–60 minutes limit the damage of a leaked token; refresh tokens and client secrets are the long-lived secrets to protect.
  • Do not put authorisation data in ID-token-only claims. If you need groups or customer IDs at the API, make sure they are in the access token (Cognito can customise access tokens with a pre-token-generation trigger on the Essentials or Plus plan ⚠ VERIFY plan requirement).
  • Public clients (mobile apps, SPAs) must not have secrets. Use authorisation code with PKCE for them.
  • Separate roles per host and environment. Never share one IAM role across dev and production, or across unrelated services.

Banking use case

Harbourline exposes the Accounts API to two kinds of callers:

  • Back-office systems (the statement generator, the complaints tool) use client credentials with dedicated app clients, each granted only the scopes it needs (accounts.read, or a future transactions.read). The API's AllowedClientIds lists them explicitly. Secrets are in Secrets Manager and rotated quarterly.
  • The mobile app signs customers in with authorisation code + PKCE against a customer user pool on the Plus plan (MFA and threat protection). Customer-facing endpoints derive the customer from the token's subject, never from the URL.

All requests pass AWS WAF, then an API Gateway JWT authorizer that rejects missing or malformed tokens cheaply, then the full validation in the API. Access decisions and failures (401/403) are logged with correlation IDs and the client_id, so the security team can see which system called what. A periodic access review checks that every app client still needs its scopes, which is evidence for the bank's access-management controls.

Common mistakes

  • Validating signature but not issuer → tokens from any Cognito pool accepted → ValidIssuer pinned to your pool.
  • Accepting ID tokens → front ends call back-end APIs with identity tokens → require token_use = access.
  • Turning off audience validation and stopping there → any client of the pool can call → check client_id against an allow-list.
  • HasClaim("scope", "x") → works with one scope, fails with two → split the space-separated claim.
  • Leaving MapInboundClaims on → FindFirstValue("sub") returns null → set it to false.
  • A new token per request → high latency and a bill for every call → cache until shortly before expiry.
  • Using the task execution role for app permissions → the app either cannot reach DynamoDB, or the execution role becomes over-privileged → app permissions belong on the task role.

Troubleshooting

SymptomLikely causeFix
Every call returns 401, log says IDX10500: Signature validation failed. No security keys were providedAuthority wrong, so JWKS download failedUse https://cognito-idp.<region>.amazonaws.com/<pool-id>, no trailing slash, no domain URL
401 with IDX10205: Issuer validation failedToken from another pool or RegionCheck the iss claim (decode the JWT) against ValidIssuer
401 with The token was issued to an app client that may not call this APIClient not in AllowedClientIdsAdd the client id to configuration
401 with token_use must be 'access'Caller sent the ID tokenSend the access token
403Token valid but lacks the scopeAllow the scope on the app client and request it in the token call
invalid_client from /oauth2/tokenWrong secret, or client has no secretRecreate with --generate-secret; check Basic auth encoding
invalid_scopeScope not allowed on the client or misspeltScope must be identifier/scope exactly
unauthorized_clientclient_credentials not enabled on the clientEnable the flow and AllowedOAuthFlowsUserPoolClient
App gets AccessDeniedException calling DynamoDBTask role missing permissions (token is irrelevant here)Fix the task role policy

Cost and cleanup

  • User pools with Lite or Essentials include 10,000 monthly active users free for direct sign-in users; this lesson creates no users.
  • Machine-to-machine token requests cost USD 0.00225 each in us-east-1 with no free tier. Twenty test tokens cost about USD 0.05. Label: 🟡 credits.
  • Free alternative: run the lab's AuthenticationTests (local signing key, no AWS) and read the token contents in this lesson.
# Deleting the domain first is required before deleting the pool
aws cognito-idp delete-user-pool-domain --user-pool-id "$POOL_ID" --domain hl-m03-<your-initials>-auth --profile learn-sandbox
aws cognito-idp delete-user-pool --user-pool-id "$POOL_ID" --profile learn-sandbox

# Confirm nothing tagged for this lesson remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab Key=Lab,Values=m03-auth \
  --query "ResourceTagMappingList[].ResourceARN" --profile learn-sandbox

Exercises

  • 🟢 Guided: Run the lab tests and read AuthenticationTests. Then temporarily change ValidateIssuer = true to false in AuthSetup.cs, rerun, and note which test fails. Revert.
  • 🟡 Challenge: Add a second policy transactions:read requiring the scope harbourline-accounts/transactions.read, apply it only to the transactions endpoint, and add tests proving a token with only accounts.read gets 403 there but 200 on /v1/accounts/{id}.
  • 🔴 Live problem: A partner reports that calls fail with 401 every day between roughly 09:00 and 09:05, then work again. Their integration fetches a token at 08:00 each morning and reuses it all day. Explain what is happening and what you would recommend to them and change on your side (if anything).

Assignment

Write an API access design page for your portfolio: the callers of the Accounts API, the OAuth flow each uses, app clients and scopes, token lifetimes, where tokens are validated (edge and app), how data-level authorisation works for customer-facing endpoints, and the IAM role of each host with its policy. Include the 8 authentication tests as the acceptance criteria.

Solutions

Knowledge check

Interview questions

  • "How do you validate a Cognito access token in ASP.NET Core?" — AddJwtBearer with Authority set to the pool's issuer, pinned ValidIssuer, lifetime validation, MapInboundClaims = false, then in OnTokenValidated require token_use = access and an allowed client_id; scopes enforced with authorisation policies that split the scope claim.
  • "Difference between the ECS task role and task execution role?" — Execution role: ECS agent pulls images, fetches secrets for injection, writes logs. Task role: your application's AWS permissions.
  • "How do you stop users reading other customers' accounts?" — Derive the customer from the verified token, never from user input; enforce it in the data access layer; test it; consider Verified Permissions for complex rules.
  • "Client credentials in a bank: what are the risks?" — Long-lived client secrets. Store them in Secrets Manager, rotate, restrict scopes per client, cache tokens, monitor token issuance, and prefer private connectivity for internal callers.

Certification practice

Completion checklist

  • I can explain user identity, client identity and service (IAM) identity
  • I can list the Cognito access-token checks: signature, issuer, lifetime, token_use, client_id, scope
  • I ran the lab's AuthenticationTests and broke/repaired one check
  • I can explain why scopes alone do not provide data-level authorisation
  • I can explain task role versus task execution role
  • I deleted any user pool and domain I created

Key takeaways

  • Accept access tokens only, pin the issuer, check client_id (Cognito has no aud in access tokens) and scopes.
  • 401 = not authenticated; 403 = authenticated but not allowed.
  • Scopes say what kind of access; data-level rules come from the verified subject, never from user input.
  • Your code's IAM role is a separate identity; keep it least-privilege on every host.
  • Cache client-credentials tokens: they are billed per request, and tests with locally signed tokens keep the rules from eroding.

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