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.
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 noaud), 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 itsSecurity/AuthSetup.csand 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:
- 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
issclaimed. Lesson: pin the issuer. - 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 = accessand scopes. - 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
customerIdquery 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:
| Concept | What it is |
|---|---|
| User pool | The directory and token issuer. Its issuer URL is https://cognito-idp.<region>.amazonaws.com/<pool-id> |
| App client | A registered application allowed to get tokens. A confidential client has a secret; a public client (mobile/SPA) does not |
| Domain | Hosts the OAuth endpoints (/oauth2/authorize, /oauth2/token) and managed login pages |
| Resource server | Represents your API, with an identifier (harbourline-accounts) and custom scopes (accounts.read). Scopes appear as <identifier>/<scope> |
| JWKS | The 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 containclient_id. Libraries that require an audience must be configured to checkclient_idinstead (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 equivalent | What's different |
|---|---|---|
| Microsoft Entra ID / Entra External ID (B2C) | Amazon Cognito user pools | Issuer URL and claim names differ; access tokens have client_id, not aud |
| App registration "Expose an API" + scopes | Cognito resource server + custom scopes | Scope 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 certificate | Cognito app client with secret, client credentials grant | Billed per token request |
AddMicrosoftIdentityWebApi | AddJwtBearer with Authority = Cognito issuer | No AWS-specific middleware needed |
APIM validate-jwt policy | API Gateway JWT authorizer (HTTP APIs) or Cognito authorizer (REST APIs) | Validation at the edge, before your code runs |
| Managed identity for the app | IAM role for the ECS task / Lambda function / EC2 instance profile | Temporary 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 token | Access token | |
|---|---|---|
| Audience | The client app that signed the user in (aud = client id) | The API (Cognito puts client_id, no aud) |
| Purpose | Tell the client who signed in (name, email) | Authorise calls to resource servers |
| Contains scopes | No | Yes, in scope (space-separated) |
token_use claim | id | access |
| Contains personal data | Often (email, name, custom attributes) | Minimal (sub, username, groups) |
| Should your API accept it? | No | Yes |
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:
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:
AddAuthentication(JwtBearerDefaults.AuthenticationScheme)— the default scheme readsAuthorization: Bearer ....jwt.Authority = options.Authority— the user pool issuer URL. The handler fetches{Authority}/.well-known/openid-configuration, findsjwks_uri, downloads the public keys and caches them, refreshing periodically and when an unknown key ID appears (so Cognito key rotation just works).MapInboundClaims = false— by default the handler renames claims to long WS-Federation URIs (subbecomeshttp://schemas.xmlsoap.org/...nameidentifier). Turning that off keeps Cognito's claim names, soFindFirstValue("client_id")works.ValidateIssuer = true, ValidIssuer = Authority— pins the issuer. A token signed by any other pool, even a genuine Cognito pool in another account, fails.ValidateAudience = false— necessary because Cognito access tokens have noaud. The audience check is replaced by theclient_idcheck in step 8. Never turn off audience validation without that replacement.ValidateLifetime = true, ClockSkew = 1 minute— rejects expired tokens. The default skew is five minutes; one minute is enough for AWS hosts with synchronised clocks.token_use != "access"→context.Fail(...)— rejects ID tokens, which are signed by the same keys and would otherwise pass every other check.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.AddPolicy(AccountsReadPolicy, ...)— the named policyaccounts:read, applied to the whole/v1route group withRequireAuthorization(AuthSetup.AccountsReadPolicy).HasScope— OAuth 2.0 puts all scopes into one space-separatedscopeclaim. A naiveHasClaim("scope", "harbourline-accounts/accounts.read")fails as soon as a token carries two scopes. The lab has aTheorytest 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:
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:
| Test | Expected |
|---|---|
No_token_is_401 | 401 |
A_valid_access_token_with_the_scope_is_200 | 200 |
A_valid_token_without_the_scope_is_403 | 403 |
An_id_token_is_rejected | 401 |
A_token_for_another_app_client_is_rejected | 401 |
A_token_from_another_user_pool_is_rejected | 401 |
An_expired_token_is_rejected | 401 |
Health_checks_stay_anonymous_so_load_balancers_can_call_them | 200 |
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:
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.
| Host | Role | Trusted principal | Notes |
|---|---|---|---|
| ECS task | Task role | ecs-tasks.amazonaws.com | Used by your app. Distinct from the task execution role, which ECS uses to pull images and write logs |
| Lambda | Execution role | lambda.amazonaws.com | Used by your function code |
| EC2 / Beanstalk | Instance profile wrapping a role | ec2.amazonaws.com | Retrieved 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 Core | API Gateway JWT authorizer | |
|---|---|---|
| Works on every host (Beanstalk, ECS, Lambda) | Yes | Only behind API Gateway |
| Rejects bad tokens before compute runs (cost, DoS) | No | Yes |
Custom checks (token_use, data-level rules) | Yes | Issuer, audience/client_id, expiry, scopes only |
| Testable in unit/integration tests | Yes | Only 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, scopeaccounts.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 # 401The 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
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.
<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>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
AddAWSService<IAmazonSecretsManager>()— the client secret comes from Secrets Manager using the worker's own IAM role. The secret never sits inappsettings.json.AddHttpClient<CognitoTokenProvider>()— a typed client for the token endpoint;IHttpClientFactorymanages its connections.AddHttpMessageHandler<BearerTokenHandler>()— every request through theaccountsclient gets a token automatically; callers never touch tokens.SemaphoreSlim _gatewith 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.FormUrlEncodedContentwithgrant_type=client_credentialsandscope— the OAuth 2.0 token request. Requesting only the scope you need is least privilege for tokens.Basicauthentication with URL-encoded id and secret — theclient_secret_basicmethod that Cognito's token endpoint accepts for confidential clients.AddSeconds(ExpiresIn).AddMinutes(-1)— refresh before expiry so an in-flight request never carries a token that expires mid-call.NightlyChecklogs 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
Authorizationheader 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 futuretransactions.read). The API'sAllowedClientIdslists 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 →
ValidIssuerpinned 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_idagainst an allow-list. HasClaim("scope", "x")→ works with one scope, fails with two → split the space-separated claim.- Leaving
MapInboundClaimson →FindFirstValue("sub")returns null → set it tofalse. - 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
| Symptom | Likely cause | Fix |
|---|---|---|
Every call returns 401, log says IDX10500: Signature validation failed. No security keys were provided | Authority wrong, so JWKS download failed | Use https://cognito-idp.<region>.amazonaws.com/<pool-id>, no trailing slash, no domain URL |
401 with IDX10205: Issuer validation failed | Token from another pool or Region | Check the iss claim (decode the JWT) against ValidIssuer |
401 with The token was issued to an app client that may not call this API | Client not in AllowedClientIds | Add the client id to configuration |
401 with token_use must be 'access' | Caller sent the ID token | Send the access token |
| 403 | Token valid but lacks the scope | Allow the scope on the app client and request it in the token call |
invalid_client from /oauth2/token | Wrong secret, or client has no secret | Recreate with --generate-secret; check Basic auth encoding |
invalid_scope | Scope not allowed on the client or misspelt | Scope must be identifier/scope exactly |
unauthorized_client | client_credentials not enabled on the client | Enable the flow and AllowedOAuthFlowsUserPoolClient |
App gets AccessDeniedException calling DynamoDB | Task 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-sandboxExercises
- 🟢 Guided: Run the lab tests and read
AuthenticationTests. Then temporarily changeValidateIssuer = truetofalseinAuthSetup.cs, rerun, and note which test fails. Revert. - 🟡 Challenge: Add a second policy
transactions:readrequiring the scopeharbourline-accounts/transactions.read, apply it only to the transactions endpoint, and add tests proving a token with onlyaccounts.readgets 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
A_token_from_another_user_pool_is_rejected fails: it now returns 200. The test's local signing key validates the signature, and without issuer validation nothing checks who issued the token. In real life the signature check would use keys downloaded from the configured authority, so a foreign pool's token would fail on signature, but only as long as the configuration never takes keys from the token's own iss. Pinning the issuer is the explicit, testable control. This is why the test exists.
In AddAccountsAuth, add .AddPolicy("transactions:read", p => p.RequireAuthenticatedUser().RequireAssertion(ctx => HasScope(ctx.User, "harbourline-accounts/transactions.read"))). In MapAccountEndpoints, keep the group policy for the account endpoints and add .RequireAuthorization("transactions:read") to the transactions route (endpoint metadata combines: both policies must pass, which is what you want, or move the group policy to individual routes). Tests: factory.CreateToken(scope: "harbourline-accounts/accounts.read") → 403 on /v1/accounts/ACC-0000000001/transactions, 200 on /v1/accounts/ACC-0000000001; and a token with both scopes → 200 on both. Also add the scope to the resource server and the client's allowed scopes in IaC.
The access token is valid for 60 minutes. A token fetched at 08:00 expires at 09:00; the partner keeps sending it, gets 401 until some retry logic eventually fetches a new one. Recommend: cache tokens using expires_in, refresh a minute before expiry, and on a 401 refresh once and retry the request once. On your side: nothing is wrong, do not lengthen the token lifetime to hide a client bug. You could improve the 401 response with a WWW-Authenticate: Bearer error="invalid_token", error_description="The token expired" header (the JWT handler sets this) and make sure your API documentation explains token caching.
Knowledge check
Answer: Cognito access tokens contain client_id instead of an aud claim, so a standard audience check would reject every valid token. The API replaces it with an explicit allow-list check on client_id in OnTokenValidated.
Answer: 403 Forbidden. The caller is authenticated (valid token); it is not authorised for this operation. 401 means "authenticate (again)", which would mislead clients into fetching new tokens pointlessly.
Answer: The task role. The task execution role (used by ECS for image pulls and log delivery) is evidently fine; the application's SDK calls use the task role.
Answer: OAuth 2.0 encodes all granted scopes in one string separated by spaces. Comparing the whole claim value with a single scope works only when exactly one scope was granted.
Answer: Gateway: invalid requests are rejected before any compute runs (cheaper, less attack surface). App: works on every host and allows full rules (token_use, data-level checks) that are covered by automated tests. Defence in depth uses both.
Interview questions
- "How do you validate a Cognito access token in ASP.NET Core?" —
AddJwtBearerwithAuthorityset to the pool's issuer, pinnedValidIssuer, lifetime validation,MapInboundClaims = false, then inOnTokenValidatedrequiretoken_use = accessand an allowedclient_id; scopes enforced with authorisation policies that split thescopeclaim. - "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
A developer protects an API with Amazon Cognito. A mobile app signs users in and calls the API with the ID token. A security review requires that the API accept only tokens intended for API authorisation and enforce custom scopes. What should the developer change?
A. Keep using the ID token and add the scopes as custom attributes.
B. Configure a resource server with custom scopes, have the app request those scopes, send the access token, and have the API require token_use = access and the scope.
C. Use the refresh token as the bearer token because it lives longer.
D. Disable token signature validation and check the email claim.
Answer: B. Access tokens carry scopes and are meant for resource servers. A misuses identity tokens. C: refresh tokens are not JWT bearer credentials for APIs and must never be sent to them. D removes the core security check.
An API validates JWT signatures by downloading keys from the URL in each token's iss claim. A penetration tester gains access by creating their own Cognito user pool. What is the root cause and fix?
A. The tokens were not encrypted; enable JWE. B. The API does not pin the issuer; configure a fixed authority and valid issuer for the bank's user pool. C. The access token lifetime is too long; reduce it to 5 minutes. D. Cognito does not sign tokens; switch to another provider.
Answer: B. Trusting the token's own issuer lets anyone who runs an identity provider sign valid-looking tokens. A, C do not address trust. D is false: Cognito signs tokens with RS256.
A .NET application on Amazon ECS with AWS Fargate must read items from one DynamoDB table. Which approach follows AWS best practice?
A. Store an IAM user's access keys as environment variables in the task definition.
B. Attach a task role with dynamodb:GetItem and dynamodb:Query on that table's ARN.
C. Add AmazonDynamoDBFullAccess to the task execution role.
D. Hard-code temporary credentials obtained with aws sts get-session-token.
Answer: B. The task role provides automatically rotated temporary credentials scoped to the needed actions and resource. A uses long-lived keys. C uses the wrong role and far too many permissions. D expires and puts credentials in code.
A company exposes a Lambda-based API through Amazon API Gateway HTTP API. It wants unauthenticated requests rejected before any Lambda invocation, using its Cognito user pool. What should it configure?
A. A Lambda authorizer that calls Cognito for every request. B. A JWT authorizer on the HTTP API with the user pool as issuer and the app client ID as audience. C. Resource policies on the Lambda function allowing only Cognito. D. AWS WAF with a rule that checks for an Authorization header.
Answer: B. HTTP API JWT authorizers validate Cognito tokens natively without invoking Lambda. A invokes Lambda (cost, latency). C controls who can invoke the function, not user authentication. D only checks presence, not validity.
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
AuthenticationTestsand 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 noaudin 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.
Logging and errors for .NET on AWS
Write structured JSON logs with correlation IDs from ASP.NET Core, ship them to CloudWatch Logs from Beanstalk, ECS and Lambda, query them with Logs Insights, and return safe RFC 9457 ProblemDetails from a global exception handler.
Background processing: worker services, SQS consumers and scheduled jobs
Move slow and scheduled work out of the request path: .NET Worker Services on Fargate, SQS consumers with long polling, visibility timeouts, idempotency and dead-letter queues, Lambda SQS triggers with partial batch responses, and EventBridge Scheduler jobs.