Open Banking and PSD2-style APIs: consent, OAuth 2.0/OIDC and FAPI basics
Understand how a bank exposes account and payment APIs to licensed third parties: the consent lifecycle, the redirect flow with PAR and PKCE, strong customer authentication, certificate-bound tokens and the FAPI 2.0 Security Profile, and how those pieces map onto API Gateway mTLS, Lambda authorizers and a consent store on AWS.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.DynamoDBv2 4.x) · FAPI 2.0 Security Profile (Final, 2025) · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Compliance boundary
This lesson explains patterns with fictional data. Open Banking and PSD2 obligations depend on your jurisdiction, licence and the standard your market mandates (for example, the UK Open Banking standard or the Berlin Group NextGenPSD2 framework in parts of the EU). A real implementation needs review by your bank's legal, compliance and security teams. Nothing here claims conformance with any standard.
Learning objectives
By the end of this lesson you can:
- Explain PSD2-style open banking in plain terms: the roles (bank, AISP, PISP, TPP), what consent is, and why strong customer authentication (SCA) happens at the bank.
- Walk through the consent lifecycle and the redirect flow step by step: client credentials, consent creation, PAR, authorization code with PKCE, SCA, token exchange and API calls.
- Describe what FAPI adds on top of OAuth 2.0 and OIDC: confidential clients with
private_key_jwtor mTLS, sender-constrained tokens (mTLS-bound or DPoP), PAR, short-lived codes and issuer checks. - Map the pattern to AWS: API Gateway REST API with mutual TLS on a custom domain, a Lambda authorizer that checks certificate binding and consent, and a DynamoDB consent store, and state honestly where Amazon Cognito does and does not fit.
- Implement, in C#, a consent state machine, PKCE generation, and a certificate-bound token check.
Prerequisites
- Cognito user pools and Lambda authorizers
- REST API design and Idempotency keys (payment initiation must be idempotent)
- Certificates, TLS and mTLS — client certificates and trust stores
- API security — BOLA applies doubly when a third party calls on a customer's behalf
- Tools: .NET 10 SDK (or Docker). No AWS account needed for the code; the AWS parts are design and optional CLI
Why this matters in banking
A budgeting app, Penny Pal (fictional), wants to show Harbourline customers all their balances in one place, and a lender wants to read 12 months of transactions to make an affordability decision. Before open banking, these firms asked customers for their online banking password and "screen-scraped" the website. The bank could not tell the app from the customer, could not limit what the app saw, and the customer could not revoke access without changing their password.
PSD2 in the EU and the UK's Open Banking programme replaced that with dedicated APIs: the third party is licensed and identified by a certificate, the customer authenticates at the bank, the customer consents to specific data for a specific period, and the customer can revoke it at any time. For the bank, getting this wrong means either leaking account data to the wrong party or blocking legitimate competitors, and both have regulatory consequences.
The idea in plain language
Four parties are involved:
| Role | Who | Example |
|---|---|---|
| PSU (payment service user) | The customer | Alex, customer CUS-00012345 |
| ASPSP (account servicing payment service provider) | The bank holding the account | Harbourline Bank |
| AISP (account information service provider) | Licensed firm reading account data with consent | Penny Pal |
| PISP (payment initiation service provider) | Licensed firm starting a payment from the account with consent | A checkout provider |
AISPs and PISPs are TPPs (third-party providers). The flow always has the same shape:
- The TPP proves who it is (a certificate issued under the market's trust framework, plus OAuth client credentials).
- The TPP asks the bank to create a consent: "read balances and transactions for accounts Alex chooses, until 2027-02-18".
- The TPP redirects Alex to the bank. Alex logs in with SCA (two of: something you know, have or are), sees what is being requested, chooses accounts and approves.
- The bank sends Alex back to the TPP with a short-lived authorization code. The TPP exchanges it for an access token tied to that consent and to the TPP's certificate.
- The TPP calls the bank's APIs with that token. Every call is checked against the consent: status, expiry, permissions and selected accounts.
- Alex can revoke the consent at the bank or the TPP at any time; tokens stop working.
Analogy: It is like giving a letting agent a key to your flat. You do not hand over your own keys (password). You go to the building's front desk yourself (authenticate at the bank), and the desk issues a key card for the agent that opens only the rooms you chose, only until a date, and only works when the agent also shows their company ID badge (certificate-bound token). You can phone the desk and cancel the card at any time.
OAuth 2.0 provides the delegation (code, tokens, scopes). OpenID Connect (OIDC) adds identity tokens and discovery. FAPI (Financial-grade API) is a set of OpenID Foundation profiles that tighten OAuth for high-value data: it removes weak options and requires proof that the token is being used by the client it was issued to.
What problem the AWS services solve
AWS does not provide an "open banking product". You compose one, and the authorization server is the part that needs the most care.
| Need | AWS building block | Honest limitations |
|---|---|---|
| Mutual TLS from TPPs | API Gateway custom domain with mTLS (REST and HTTP APIs); trust store (PEM bundle) in S3 | Regional custom domain required; you must keep the trust store current with the scheme's CA certificates and handle revocation yourself (for example, in a Lambda authorizer) |
| Per-request token, certificate and consent checks | Lambda authorizer (REQUEST type), which can read $context.identity.clientCert.* | Authorizer caching must include the certificate and token, or one TPP's decision could be reused for another |
| Consent store | DynamoDB (consent by ID, by customer, by TPP) with point-in-time recovery | You design the state machine and audit trail |
| Authorization server (FAPI) | Amazon Cognito for customer sign-in and MFA, or a separate FAPI-certified authorization server running on ECS/EKS, or a managed third-party service | Cognito user pools do not natively provide PAR, DPoP or certificate-bound access tokens, and are not listed as FAPI-certified ⚠ VERIFY current Cognito features and the OpenID certification list before deciding |
| Signing keys | AWS KMS asymmetric keys (RSA/ECC) for signing JWTs and responses | KMS signs digests; you build the JWS around it |
| Audit | CloudTrail, access logs, consent events to an immutable store | Retention periods are a compliance decision |
The honest architecture decision for most banks: use Cognito (or your existing IdP) to authenticate the customer, and a FAPI-certified authorization server to issue tokens to TPPs, or buy a managed open banking gateway. Writing your own authorization server is high risk.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Entra ID / Azure AD B2C as OAuth server | Amazon Cognito user pools | Neither is a FAPI-certified authorization server out of the box ⚠ VERIFY; both are fine for customer sign-in |
APIM validate-client-certificate policy | API Gateway mTLS custom domain + Lambda authorizer | Trust store in S3; per-certificate checks in your authorizer |
APIM validate-jwt with cnf checks | Lambda authorizer comparing cnf.x5t#S256 with the presented certificate | You write the binding check |
| Cosmos DB consent container | DynamoDB consent table | Same design ideas: partition by consent ID, GSIs for customer and TPP |
| Key Vault signing keys | AWS KMS asymmetric keys | Sign with kms:Sign, publish public keys as a JWKS |
Microsoft.IdentityModel JWT handling | Same library in .NET on AWS | Unchanged |
Architecture
Security-boundary view.
- Trust framework zone: TPP identity comes from certificates issued under the market's scheme (in the EU, eIDAS qualified certificates: QWAC for TLS, QSealC for signing; in the UK, certificates issued by the Open Banking directory ⚠ VERIFY current UK certificate requirements). Your trust store contains only those issuing CAs.
- Edge: API Gateway terminates mTLS; nothing reaches the authorizer without a certificate that chains to the trust store.
- Decision point: the authorizer combines three facts: valid token, token bound to this certificate, consent active and covering the request.
- Data: the Accounts API returns only accounts listed in the consent, even if the customer has more.
Step-by-step implementation
Onboard the TPP
The TPP registers with your bank, typically through dynamic client registration (RFC 7591) using a signed software statement from the scheme's directory. You record its client ID, its certificate subject or thumbprint, its JWKS URL, its roles (AISP, PISP) and its redirect URIs. Validate redirect URIs exactly; no wildcards.
Create the consent (TPP to bank, no customer yet)
The TPP gets a client-credentials token and calls POST /account-access-consents with requested permissions (for example ReadAccountsBasic, ReadBalances, ReadTransactionsDetail) and an expiration date. The bank stores the consent in status AwaitingAuthorisation, linked to the TPP's client ID, and returns a ConsentId. Payment consents also carry the amount, currency and creditor, and are idempotent on the TPP's x-idempotency-key.
Send the customer to the bank with PAR and PKCE
The TPP sends its authorization request directly to the bank (pushed authorization request, RFC 9126), as a signed request object containing the ConsentId (in the UK standard, an openbanking_intent_id claim ⚠ VERIFY claim name in your standard version), redirect_uri, state, nonce and a PKCE code_challenge (S256). The bank returns a request_uri, and the TPP redirects the customer to the bank with only client_id and request_uri. Nothing sensitive travels through the browser URL.
Authenticate the customer with SCA and capture the decision
The bank's own login (Cognito with MFA, or the existing digital-banking IdP) authenticates the customer. The consent screen shows the TPP's registered name, the permissions in plain words and the expiry, and lets the customer select accounts. On approval, the consent moves to Authorised with CustomerId and AccountIds. On cancel, Rejected.
Exchange the code for a sender-constrained token
The bank redirects back with code, state and iss (RFC 9207, so the TPP can detect mix-up attacks). The TPP calls the token endpoint over mTLS, sending the PKCE code_verifier. The bank issues an access token whose cnf claim contains x5t#S256, the SHA-256 thumbprint of the TPP's certificate (RFC 8705). A stolen token is useless without the matching private key. FAPI 2.0 also allows DPoP (RFC 9449) as the binding method.
Check every API call against the consent
The Lambda authorizer validates the token signature and claims, compares cnf.x5t#S256 with the certificate API Gateway saw, loads the consent and checks: status Authorised, not expired, permission covers the route (GET /accounts/{id}/balances needs ReadBalances), and the account is in the consented list. It returns Allow with the consent ID and account list in the context. The backend filters by that list.
Support revocation and expiry everywhere
Revocation can come from the customer's banking app ("Connected apps" screen), from the TPP (DELETE /account-access-consents/{id}), or from expiry. All of them set status Revoked or Expired, revoke refresh tokens and are seen by the authorizer on the next call. Keep authorizer cache TTL short (seconds, not minutes) so revocation takes effect quickly.
AWS Console instructions
- mTLS custom domain: Console → API Gateway → Custom domain names → Create → enter
ob.harbourline.example→ endpoint type Regional → choose an ACM certificate for the domain → enable Mutual TLS authentication → Truststore URIs3://hl-m04-truststore/truststore.pem(optionally a version) → Create. Then API mappings → map the REST API stage. - Disable the default endpoint: API → Settings → Default endpoint → Disabled, so TPPs cannot bypass mTLS through the
execute-apiURL. - Authorizer: API → Authorizers → Create → Lambda, type Request, identity source: header
Authorization; set Authorization caching off or to a few seconds. The authorizer reads the client certificate from the request context of its input event (requestContext.identity.clientCert), which API Gateway populates on mTLS custom domains ⚠ VERIFY the exact event shape in the Lambda authorizer input documentation. - Consent table: DynamoDB → Create table
hl-m04-consents, partition keyConsentId(string), on-demand capacity, encryption with an AWS owned or customer managed key, point-in-time recovery on. Add GSIsByCustomer(CustomerId) andByClient(ClientId).
AWS CLI
PROFILE=learn-sandbox
REGION=us-east-1
# 1. Upload the trust store: concatenated PEM CA certificates of the scheme (fictional test CA here)
aws s3api create-bucket --bucket hl-m04-truststore-111122223333 --profile $PROFILE --region $REGION
aws s3api put-public-access-block --bucket hl-m04-truststore-111122223333 \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true \
--profile $PROFILE --region $REGION
aws s3api put-bucket-versioning --bucket hl-m04-truststore-111122223333 \
--versioning-configuration Status=Enabled --profile $PROFILE --region $REGION
aws s3 cp truststore.pem s3://hl-m04-truststore-111122223333/truststore.pem --profile $PROFILE --region $REGION
# 2. Create a Regional custom domain with mutual TLS (needs an ACM certificate you own for the domain)
aws apigateway create-domain-name --domain-name ob.harbourline.example \
--regional-certificate-arn arn:aws:acm:us-east-1:111122223333:certificate/EXAMPLE \
--endpoint-configuration types=REGIONAL \
--security-policy TLS_1_2 \
--mutual-tls-authentication truststoreUri=s3://hl-m04-truststore-111122223333/truststore.pem \
--tags Project=cea-lab,Lab=m04-l19,Environment=learn,Owner=you \
--profile $PROFILE --region $REGION
# 3. Consent table
aws dynamodb create-table --table-name hl-m04-consents \
--attribute-definitions AttributeName=ConsentId,AttributeType=S AttributeName=CustomerId,AttributeType=S \
--key-schema AttributeName=ConsentId,KeyType=HASH \
--global-secondary-indexes 'IndexName=ByCustomer,KeySchema=[{AttributeName=CustomerId,KeyType=HASH}],Projection={ProjectionType=ALL}' \
--billing-mode PAY_PER_REQUEST \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m04-l19 Key=Environment,Value=learn Key=Owner,Value=you \
--profile $PROFILE --region $REGION
aws dynamodb update-continuous-backups --table-name hl-m04-consents \
--point-in-time-recovery-specification PointInTimeRecoveryEnabled=true \
--profile $PROFILE --region $REGIONCreating a custom domain needs a domain you control and a validated ACM certificate. If you do not have one, treat steps 1–2 as a design exercise; the consent table and code work on their own.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.DynamoDB;
using Amazon.CDK.AWS.S3;
using Constructs;
namespace Harbourline.OpenBanking.Infra;
public sealed class OpenBankingEdgeStack : Stack
{
public OpenBankingEdgeStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
{
var trustBucket = new Bucket(this, "TrustStore", new BucketProps
{
BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
Encryption = BucketEncryption.S3_MANAGED,
EnforceSSL = true,
Versioned = true,
RemovalPolicy = RemovalPolicy.DESTROY,
AutoDeleteObjects = true
});
var cert = Certificate.FromCertificateArn(this, "DomainCert",
"arn:aws:acm:us-east-1:111122223333:certificate/EXAMPLE");
var domain = new DomainName(this, "ObDomain", new DomainNameProps
{
DomainName = "ob.harbourline.example",
Certificate = cert,
EndpointType = EndpointType.REGIONAL,
SecurityPolicy = SecurityPolicy.TLS_1_2,
Mtls = new MTLSConfig { Bucket = trustBucket, Key = "truststore.pem" }
});
var consents = new TableV2(this, "Consents", new TablePropsV2
{
TableName = "hl-m04-consents",
PartitionKey = new Attribute { Name = "ConsentId", Type = AttributeType.STRING },
Billing = Billing.OnDemand(),
PointInTimeRecoverySpecification = new PointInTimeRecoverySpecification { PointInTimeRecoveryEnabled = true },
GlobalSecondaryIndexes = new IGlobalSecondaryIndexPropsV2[]
{
new GlobalSecondaryIndexPropsV2
{
IndexName = "ByCustomer",
PartitionKey = new Attribute { Name = "CustomerId", Type = AttributeType.STRING }
}
},
RemovalPolicy = RemovalPolicy.DESTROY
});
new CfnOutput(this, "DomainTarget", new CfnOutputProps { Value = domain.DomainNameAliasDomainName });
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m04-l19");
Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
Amazon.CDK.Tags.Of(this).Add("Owner", "you");
}
}PointInTimeRecoverySpecification replaced the older boolean property in recent CDK versions ⚠ VERIFY the property name in Amazon.CDK.Lib 2.277.0.
Complete code
A self-contained .NET 10 console app that you can run locally. It implements the three pieces you would put in the authorizer and consent service: a consent state machine, PKCE generation and verification, and a certificate-bound token check (RFC 8705 thumbprint). It creates throwaway self-signed certificates so it runs with no files and no AWS.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
</Project>using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
var clock = new FakeClock(new DateTimeOffset(2026, 11, 18, 9, 0, 0, TimeSpan.Zero));
var store = new InMemoryConsentStore();
var service = new ConsentService(store, clock);
// --- 1. TPP onboarding: Penny Pal's transport certificate (self-signed here; scheme-issued in reality)
using var pennyPalCert = Certs.CreateSelfSigned("CN=Penny Pal Ltd, O=Penny Pal, C=GB");
using var attackerCert = Certs.CreateSelfSigned("CN=Mallory, O=Not A TPP, C=GB");
const string pennyPalClientId = "tpp-pennypal-001";
// --- 2. TPP creates a consent (no customer yet)
var consent = service.Create(pennyPalClientId,
[Permission.ReadAccountsBasic, Permission.ReadBalances],
expiresAt: clock.UtcNow.AddDays(90));
Console.WriteLine($"Created {consent.ConsentId}: {consent.Status}");
// --- 3. PKCE: TPP creates verifier + challenge; challenge goes in the PAR request object
var verifier = Pkce.CreateVerifier();
var challenge = Pkce.ChallengeS256(verifier);
Console.WriteLine($"PKCE challenge (S256): {challenge}");
// --- 4. Customer authenticates with SCA at the bank and selects one of two accounts
service.Authorise(consent.ConsentId, customerId: "CUS-00012345", accountIds: ["ACC-0000123456"]);
Console.WriteLine($"After SCA: {store.Get(consent.ConsentId)!.Status}");
// --- 5. Token endpoint verifies PKCE and binds the token to the TPP's certificate
if (!Pkce.Verify(verifier, challenge)) throw new InvalidOperationException("PKCE failed");
var token = new AccessToken(
Subject: "CUS-00012345",
ClientId: pennyPalClientId,
ConsentId: consent.ConsentId,
CnfX5tS256: CertBinding.Thumbprint(pennyPalCert),
ExpiresAt: clock.UtcNow.AddMinutes(5));
// --- 6. Authorizer decisions for several API calls
var authorizer = new ConsentAuthorizer(store, clock);
Show("Penny Pal reads balance of consented account",
authorizer.Decide(token, pennyPalCert, "GET", "/accounts/ACC-0000123456/balances"));
Show("Penny Pal reads a non-consented account",
authorizer.Decide(token, pennyPalCert, "GET", "/accounts/ACC-0000123457/balances"));
Show("Penny Pal reads transactions (permission not granted)",
authorizer.Decide(token, pennyPalCert, "GET", "/accounts/ACC-0000123456/transactions"));
Show("Stolen token used with attacker's certificate",
authorizer.Decide(token, attackerCert, "GET", "/accounts/ACC-0000123456/balances"));
// --- 7. Customer revokes in the banking app; next call is denied
service.Revoke(consent.ConsentId, by: "PSU");
Show("After revocation",
authorizer.Decide(token, pennyPalCert, "GET", "/accounts/ACC-0000123456/balances"));
static void Show(string label, AuthzDecision d) =>
Console.WriteLine($"{label,-55} => {(d.Allow ? "ALLOW" : "DENY")} {d.Reason}");
// ===================== Consent model =====================
public enum ConsentStatus { AwaitingAuthorisation, Authorised, Rejected, Revoked, Expired }
public enum Permission { ReadAccountsBasic, ReadAccountsDetail, ReadBalances, ReadTransactionsBasic, ReadTransactionsDetail }
public sealed record Consent(
string ConsentId, string ClientId, IReadOnlySet<Permission> Permissions, DateTimeOffset CreatedAt,
DateTimeOffset ExpiresAt, ConsentStatus Status, string? CustomerId, IReadOnlyList<string> AccountIds,
DateTimeOffset StatusUpdatedAt);
public interface IConsentStore
{
Consent? Get(string consentId);
void Put(Consent consent, ConsentStatus? expectedStatus); // conditional write: optimistic concurrency
}
public sealed class InMemoryConsentStore : IConsentStore
{
private readonly Dictionary<string, Consent> _items = new();
private readonly Lock _gate = new();
public Consent? Get(string consentId) { lock (_gate) return _items.GetValueOrDefault(consentId); }
public void Put(Consent consent, ConsentStatus? expectedStatus)
{
lock (_gate)
{
var current = _items.GetValueOrDefault(consent.ConsentId);
if (expectedStatus is not null && current?.Status != expectedStatus)
throw new InvalidOperationException($"Consent {consent.ConsentId} is {current?.Status}, expected {expectedStatus}");
_items[consent.ConsentId] = consent;
}
}
}
public sealed class ConsentService(IConsentStore store, IClock clock)
{
private static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(365); // bank policy, not a regulatory number
public Consent Create(string clientId, IEnumerable<Permission> permissions, DateTimeOffset expiresAt)
{
var perms = permissions.ToHashSet();
if (perms.Count == 0) throw new ArgumentException("At least one permission is required.");
if (expiresAt <= clock.UtcNow || expiresAt > clock.UtcNow + MaxLifetime)
throw new ArgumentException("Expiry must be in the future and within the bank's maximum lifetime.");
var consent = new Consent($"AAC-{Guid.CreateVersion7():N}", clientId, perms, clock.UtcNow, expiresAt,
ConsentStatus.AwaitingAuthorisation, null, [], clock.UtcNow);
store.Put(consent, expectedStatus: null);
return consent;
}
public void Authorise(string consentId, string customerId, IReadOnlyList<string> accountIds)
{
var c = store.Get(consentId) ?? throw new KeyNotFoundException(consentId);
if (accountIds.Count == 0) throw new ArgumentException("Customer must select at least one account.");
store.Put(c with { Status = ConsentStatus.Authorised, CustomerId = customerId, AccountIds = accountIds,
StatusUpdatedAt = clock.UtcNow }, expectedStatus: ConsentStatus.AwaitingAuthorisation);
}
public void Revoke(string consentId, string by)
{
var c = store.Get(consentId) ?? throw new KeyNotFoundException(consentId);
store.Put(c with { Status = ConsentStatus.Revoked, StatusUpdatedAt = clock.UtcNow }, expectedStatus: ConsentStatus.Authorised);
Console.WriteLine($"Consent {consentId} revoked by {by}");
}
}
// ===================== PKCE (RFC 7636) =====================
public static class Pkce
{
public static string CreateVerifier() => Base64Url(RandomNumberGenerator.GetBytes(32)); // 43 chars
public static string ChallengeS256(string verifier) => Base64Url(SHA256.HashData(Encoding.ASCII.GetBytes(verifier)));
public static bool Verify(string verifier, string challenge) =>
CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(ChallengeS256(verifier)), Encoding.ASCII.GetBytes(challenge));
internal static string Base64Url(ReadOnlySpan<byte> bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
// ===================== Certificate binding (RFC 8705) =====================
public static class CertBinding
{
// x5t#S256 = base64url(SHA-256(DER encoding of the certificate))
public static string Thumbprint(X509Certificate2 cert) => Pkce.Base64Url(SHA256.HashData(cert.RawData));
// API Gateway passes the PEM in $context.identity.clientCert.clientCertPem
public static string ThumbprintFromPem(string pem)
{
using var cert = X509Certificate2.CreateFromPem(pem);
return Thumbprint(cert);
}
}
public sealed record AccessToken(string Subject, string ClientId, string ConsentId, string CnfX5tS256, DateTimeOffset ExpiresAt);
public sealed record AuthzDecision(bool Allow, string Reason, string? ConsentId = null, IReadOnlyList<string>? AccountIds = null);
public sealed class ConsentAuthorizer(IConsentStore store, IClock clock)
{
// Route → permission needed. Unknown routes are denied.
private static readonly (string Method, string Suffix, Permission Needed)[] Routes =
[
("GET", "/balances", Permission.ReadBalances),
("GET", "/transactions", Permission.ReadTransactionsBasic),
("GET", "", Permission.ReadAccountsBasic)
];
public AuthzDecision Decide(AccessToken token, X509Certificate2 presentedCert, string method, string path)
{
// In AWS the JWT signature, issuer, audience and expiry are validated first (Microsoft.IdentityModel).
if (token.ExpiresAt <= clock.UtcNow) return new(false, "token expired");
var presented = CertBinding.Thumbprint(presentedCert);
if (!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(presented), Encoding.ASCII.GetBytes(token.CnfX5tS256)))
return new(false, "token not bound to presented certificate");
var consent = store.Get(token.ConsentId);
if (consent is null || consent.ClientId != token.ClientId) return new(false, "unknown consent");
if (consent.Status != ConsentStatus.Authorised) return new(false, $"consent {consent.Status}");
if (consent.ExpiresAt <= clock.UtcNow) return new(false, "consent expired");
var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries); // accounts/{id}/balances
if (parts.Length < 2 || parts[0] != "accounts") return new(false, "route not covered");
var accountId = parts[1];
var suffix = parts.Length > 2 ? "/" + parts[2] : "";
var idx = Array.FindIndex(Routes, r => r.Method == method && r.Suffix == suffix);
if (idx < 0) return new(false, "route not covered");
var needed = Routes[idx].Needed;
if (!consent.Permissions.Contains(needed)) return new(false, $"permission {needed} not granted");
if (!consent.AccountIds.Contains(accountId)) return new(false, "account not in consent");
return new(true, "ok", consent.ConsentId, consent.AccountIds);
}
}
// ===================== Helpers =====================
public interface IClock { DateTimeOffset UtcNow { get; } }
public sealed class FakeClock(DateTimeOffset now) : IClock { public DateTimeOffset UtcNow { get; set; } = now; }
public static class Certs
{
public static X509Certificate2 CreateSelfSigned(string subject)
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var req = new CertificateRequest(subject, key, HashAlgorithmName.SHA256);
req.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, critical: true));
return req.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddDays(1));
}
}Expected output (IDs differ):
Created AAC-019a…: AwaitingAuthorisation
PKCE challenge (S256): 3Jk…
After SCA: Authorised
Penny Pal reads balance of consented account => ALLOW ok
Penny Pal reads a non-consented account => DENY account not in consent
Penny Pal reads transactions (permission not granted) => DENY permission ReadTransactionsBasic not granted
Stolen token used with attacker's certificate => DENY token not bound to presented certificate
Consent AAC-019a… revoked by PSU
After revocation => DENY consent RevokedCode explained line by line
FakeClockmakes time explicit. Consent logic is full of expiry rules; injecting a clock makes them testable (in .NET 8+ you can also useTimeProvider).Certs.CreateSelfSignedcreates an ECDSA P-256 certificate in memory. In production, TPP certificates are issued by the scheme's CA and validated against your trust store at the API Gateway edge.ConsentService.Createenforces that a consent has at least one permission and a bounded expiry. The maximum lifetime is a bank policy value; regulators and standards set their own rules, which your compliance team interprets.- Consent IDs are prefixed (
AAC-) and use UUID v7, so they are unique, time-ordered and not guessable from each other. store.Put(..., expectedStatus)is a conditional write: you can only authorise a consent that is stillAwaitingAuthorisation, and only revoke one that isAuthorised. In DynamoDB this is aConditionExpressiononStatus, which prevents races such as a customer approving a consent the TPP already deleted.Pkce.CreateVerifieruses 32 random bytes, giving a 43-character verifier (the minimum length RFC 7636 allows).ChallengeS256is base64url of SHA-256 of the verifier. FAPI requires S256, neverplain.Pkce.Verifyand the thumbprint comparison useCryptographicOperations.FixedTimeEqualsto avoid timing side channels.CertBinding.Thumbprintcomputesx5t#S256exactly as RFC 8705 defines: base64url-encoded SHA-256 of the DER certificate.ThumbprintFromPemshows how the authorizer computes it from the PEM that API Gateway puts in$context.identity.clientCert.clientCertPem.ConsentAuthorizer.Decideperforms the checks in order of cost and certainty: token expiry, certificate binding, consent existence and owner (ClientIdmust match, so one TPP cannot use another TPP's consent ID), status, consent expiry, route permission, account membership.- The route table maps each endpoint to the minimum permission. Unknown routes are denied: deny by default.
- The decision returns the consent ID and account list so API Gateway can pass them as authorizer context; the backend must still filter by that list (defence in depth against BOLA).
- The "stolen token" case is why FAPI requires sender-constrained tokens: the token alone is not enough without the private key behind the certificate.
Security considerations
⚠ Learning shortcut — not for production
The demo uses self-signed certificates and an in-memory token object instead of signed JWTs. In production, TPP certificates chain to the scheme's CAs in the API Gateway trust store, tokens are JWTs signed by the authorization server (for example with a KMS asymmetric key) and validated with Microsoft.IdentityModel.JsonWebTokens, and you check certificate revocation (OCSP/CRL) in the authorizer because API Gateway's trust store does not do revocation checking for you ⚠ VERIFY.
⚠ Learning shortcut — not for production
Building your own FAPI authorization server is out of scope and risky. Use a product that has passed the OpenID Foundation's FAPI conformance tests, and run those tests yourself against your deployment.
- Never let the TPP pick the customer. The customer identity comes from SCA at the bank, never from the consent request.
- Show the customer what they consent to, in plain words, including the TPP's registered name and the expiry. Dark patterns in consent screens are a conduct risk.
- Data minimisation (UK GDPR). Return only the consented accounts and permissions. Log consent events (created, authorised, revoked, used) with consent ID and TPP client ID, not account data.
- Authorizer caching. If you cache authorizer results, the cache key must include the token and the certificate; keep the TTL short so revocations take effect quickly.
- Disable the default
execute-apiendpoint, or a TPP could reach the API without mTLS. - Payment consents must bind the exact amount, currency and creditor, and be single-use; check them again at execution time, and require idempotency keys.
- Fraud and APP scams. PISP payments are still the bank's risk to monitor; feed them into the same fraud controls as other payments.
Banking use case
Harbourline's open banking platform (fictional):
- Edge:
ob.harbourline.example, REST API with mTLS, trust store containing the scheme's issuing CAs, default endpoint disabled, WAF web ACL with a per-client rate rule. - Authorization server: a FAPI-certified product on ECS Fargate in private subnets, using the bank's existing customer IdP for SCA. Cognito remains the IdP for Harbourline's own mobile app.
- Consent service: .NET 10 on Fargate, DynamoDB table with GSIs by customer and by client, conditional writes for every status change, DynamoDB Streams feeding consent events to an audit bucket with Object Lock.
- Customer experience: the mobile app's "Connected apps" screen lists consents from the
ByCustomerindex and offers one-tap revocation. - Operations: dashboards per TPP (calls, errors, latency), alarms on authorizer denials by reason, and a report of availability of the dedicated interface compared with the customer channels, because regulators may ask for it ⚠ VERIFY current reporting obligations in your market.
Common mistakes
- Treating a scope as a consent.
accountsscope says "may call account APIs"; the consent says which accounts, which data and until when. Check both. - Bearer tokens for TPPs. Without certificate or DPoP binding, a leaked token is usable by anyone.
- Long authorizer cache TTLs. Revocation appears not to work for minutes.
- Wildcard or prefix redirect URI matching. Leads to code theft; match exactly.
- Authorization request parameters in the browser URL. Use PAR so the request is authenticated and not tamperable.
- Leaving the default endpoint enabled, bypassing mTLS.
- Returning all customer accounts instead of the consented subset.
- Assuming Cognito covers FAPI without checking PAR, binding and certification.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| TPP gets TLS handshake failure | Client certificate not chaining to a CA in the trust store, or trust store version stale | Add the issuing and intermediate CAs to the PEM, upload, update the domain's trust store version |
| Custom domain shows trust store warnings | Invalid or expired certificates in the PEM bundle | Check the domain's warnings in API Gateway; remove bad entries |
Calls succeed via execute-api URL without a certificate | Default endpoint still enabled | Disable it on the API |
| Authorizer always denies with "not bound" | Thumbprint computed over PEM text instead of DER bytes, or base64 instead of base64url | Hash cert.RawData; use base64url without padding |
| Revocation takes minutes to apply | Authorizer cache TTL too long | Lower TTL or disable caching for consent-bearing routes |
Consent stuck in AwaitingAuthorisation | Customer abandoned the journey | Expire unauthorised consents after a short window with a DynamoDB TTL or scheduled job |
ConditionalCheckFailedException on authorise | Consent was already rejected, revoked or authorised | Return a clear error to the TPP; do not overwrite |
Cost and cleanup
- Free: the C# demo runs locally. The architecture is a design exercise.
- Optional AWS pieces: a DynamoDB on-demand table and an S3 trust store bucket cost effectively nothing at lab volume. A Regional custom domain has no hourly charge, but you need a domain and an ACM certificate you control. A REST API is billed per request. Do not deploy a third-party authorization server for the lab.
aws apigateway delete-domain-name --domain-name ob.harbourline.example --profile learn-sandbox --region us-east-1
aws dynamodb delete-table --table-name hl-m04-consents --profile learn-sandbox --region us-east-1
aws s3 rm s3://hl-m04-truststore-111122223333 --recursive --profile learn-sandbox --region us-east-1
# Versioned bucket: delete object versions too (or use the console "Empty" action) before deleting the bucket
aws s3api delete-bucket --bucket hl-m04-truststore-111122223333 --profile learn-sandbox --region us-east-1
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--query 'ResourceTagMappingList[].ResourceARN' --profile learn-sandbox --region us-east-1Exercises
- 🟢 Guided: Run the demo. Then add
Permission.ReadTransactionsBasicto the consent request and confirm the transactions call is allowed. Advance theFakeClockby 91 days and confirm every call is denied with "consent expired". - 🟡 Challenge: Add a
DomesticPaymentConsentwithAmount(decimal),Currency,CreditorIban,Statusand single-use semantics: the firstPOST /domestic-paymentswith matching details moves it toConsumed; a second attempt with the same consent is rejected, and a retry with the samex-idempotency-keyreturns the original result. - 🔴 Live problem: A TPP complains that "since your certificate rotation last night, half our calls fail with 403 not-bound". Their new certificate went live at 22:00; tokens issued before 22:00 have a 1-hour lifetime and refresh tokens are valid for 90 days. Explain what is happening, what the TPP should do, and whether the bank should change anything.
Assignment
Write a two-page open banking design note for Harbourline: roles, consent lifecycle diagram with statuses and transitions, the checks your authorizer performs (in order), where SCA happens, what you log, how revocation propagates, and an explicit "decisions needing compliance review" list. Use fictional data only.
Solutions
Add the permission in service.Create(...), and the transactions call returns ALLOW ok. Then add clock.UtcNow = clock.UtcNow.AddDays(91); before the calls. The first failing check is now token expiry (the token was issued for 5 minutes), which is correct; to see "consent expired", issue a fresh token after advancing the clock. Why: the authorizer checks cheaper, more general conditions first, and both the token and the consent must be valid.
Model DomesticPaymentConsent(string ConsentId, string ClientId, decimal Amount, string Currency, string CreditorIban, PaymentConsentStatus Status) with statuses AwaitingAuthorisation → Authorised → Consumed. In the payment handler: (1) look up the idempotency record for (ClientId, x-idempotency-key) and return the stored response if present; (2) load the consent and compare amount, currency and creditor exactly with the payment request; (3) conditionally update the status from Authorised to Consumed; (4) create the payment and store the response under the idempotency key in the same transaction (DynamoDB TransactWriteItems). Why: the conditional status change makes the consent single-use even under concurrent requests, and the idempotency record makes network retries safe, as in Idempotency keys.
Tokens issued before 22:00 are bound to the old certificate's thumbprint. Calls that present the new certificate with an old access token fail the binding check, which is correct behaviour. The TPP should obtain new tokens (refresh or re-run client credentials) using the new certificate after switching; refresh at the token endpoint over mTLS binds the new access token to the new certificate, if your authorization server supports re-binding on refresh ⚠ VERIFY your product's behaviour. Good practice is overlap: register the new certificate first, switch TLS and token refresh together, then retire the old one. The bank should publish rotation guidance and may monitor "not bound" denials per TPP to proactively contact them; it should not weaken the binding check.
Knowledge check
Answer: A scope is a coarse capability in the token (for example, may call account APIs). A consent is a stored, customer-approved record specifying permissions, accounts, expiry and status, checked on every call and revocable independently of tokens.
Answer: Use of a stolen token by someone else. With mTLS binding, the token's cnf.x5t#S256 must match the client certificate presented on the call; with DPoP, the caller must sign a proof with the bound key.
Answer: The authorization request is sent directly from the authenticated client to the bank, so it cannot be read or tampered with in the browser, and the bank knows it came from that client before the customer is redirected.
Answer: At the bank (ASPSP), on the bank's own pages or app. The TPP never sees the customer's banking credentials.
Answer: Mutual TLS on a custom domain name with a trust store (PEM bundle in S3). The default execute-api endpoint should be disabled so it cannot be bypassed.
Interview questions
- "Walk me through an open banking account-information flow." — TPP gets a client-credentials token, creates a consent, sends a PAR with PKCE referencing the consent, redirects the customer, customer does SCA and selects accounts, bank returns code and
iss, TPP exchanges the code over mTLS for a certificate-bound token, calls APIs that check token, binding and consent on each request. - "What does FAPI add to OAuth 2.0?" — Confidential clients only, strong client authentication (
private_key_jwtor mTLS), PAR, PKCE S256, sender-constrained tokens, short-lived codes, issuer identification, and removal of insecure options. - "Could you use Cognito for this?" — For customer sign-in and MFA, yes. For issuing FAPI-grade tokens to TPPs, check: Cognito does not natively offer PAR, DPoP or certificate-bound tokens, so a FAPI-certified authorization server is the safer choice.
- "How does revocation reach the API immediately?" — The authorizer checks consent status on every call (short or no caching), refresh tokens are revoked, and access tokens are short-lived.
- "How do you stop a TPP seeing accounts the customer didn't select?" — The consent stores selected account IDs; the authorizer passes them in context; the backend filters by them; tests prove it.
Certification practice
A bank exposes account APIs to licensed third parties through API Gateway. Tokens have leaked from a partner's logs and were replayed from unknown hosts. Which control MOST effectively prevents replay of leaked tokens?
A. Reduce the access token lifetime from 60 to 30 minutes.
B. Require mutual TLS on a custom domain and, in a Lambda authorizer, require the token's cnf.x5t#S256 to match the presented client certificate.
C. Add an AWS WAF IP reputation rule group.
D. Require an API key in addition to the token.
Answer: B. Binding the token to the client certificate means a leaked token is useless without the private key. A shortens the window but still allows replay. C blocks some known-bad IPs, not arbitrary hosts. D adds another bearer secret that can leak the same way.
A company configures mutual TLS on an API Gateway Regional custom domain for partner access. A test shows partners can still call the API without a certificate. What is the MOST likely reason?
A. The trust store is in a different Region.
B. The API's default execute-api endpoint is still enabled.
C. The ACM certificate is RSA instead of ECDSA.
D. Mutual TLS works only on edge-optimized endpoints.
Answer: B. mTLS is enforced on the custom domain only; the default endpoint bypasses it unless disabled. A would fail domain configuration. C is irrelevant. D is false: mTLS requires a Regional custom domain.
A Lambda REQUEST authorizer checks an open banking consent in DynamoDB and caches results for 300 seconds keyed on the Authorization header. Customers report that revoking access in the banking app takes up to 5 minutes to apply. What should the developer do?
A. Increase the authorizer's memory. B. Reduce or disable authorizer caching for these routes so the consent status is checked on each request. C. Switch to a TOKEN authorizer. D. Store consents in S3 instead of DynamoDB.
Answer: B. The cache reuses the earlier Allow decision until the TTL expires. A does not affect caching. C has the same caching behaviour. D makes lookups slower without fixing staleness.
Completion checklist
- I can name the open banking roles and explain consent vs scope
- I can draw the redirect flow with PAR, PKCE, SCA and a certificate-bound token
- I can list what FAPI 2.0 adds to OAuth 2.0
- I ran the demo and saw binding, permission, account and revocation checks deny correctly
- I can explain where Cognito fits and where a FAPI-certified authorization server is needed
- I ran the cleanup steps (if I deployed anything) and confirmed nothing tagged
Project=cea-labremains
Key takeaways
- Open banking replaces screen-scraping with licensed TPPs, bank-side SCA and revocable, fine-grained consents.
- Every API call must check token validity, certificate binding and consent status, permissions and accounts.
- FAPI hardens OAuth with PAR, PKCE, strong client authentication and sender-constrained tokens.
- On AWS: API Gateway mTLS custom domain (default endpoint off), Lambda authorizer, DynamoDB consent store with conditional writes; use a FAPI-certified authorization server.
- Regulations differ by market; get compliance review and never claim conformance from patterns alone.
Further reading
- FAPI 2.0 Security Profile (Final)
- OpenID Foundation FAPI Working Group
- RFC 9126: OAuth 2.0 Pushed Authorization Requests
- RFC 8705: OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens
- RFC 9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP)
- RFC 7636: Proof Key for Code Exchange (PKCE)
- Configuring mutual TLS authentication for a REST API
- Choose between REST APIs and HTTP APIs
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.
API security: AWS WAF and the OWASP API Security Top 10 for a banking API
Map every OWASP API Security Top 10 (2023) risk to a concrete control on AWS or in .NET, attach a WAF web ACL with managed and rate-based rules to an API Gateway REST API, and enforce object- and property-level authorisation in ASP.NET Core so a customer can only ever see their own accounts.
ISO 20022 message handling: pain.001, pacs.008 and camt.053 in C#
Read, build and validate ISO 20022 payment messages safely in .NET: understand the structure of pain.001, pacs.008 and camt.053, validate in three layers (schema, scheme rules, business rules), generate C# classes from XSDs, parse statements into Harbourline's transaction model, and run it all on AWS with S3, SQS and Lambda.