Digital banking platform: channels, BFF APIs, identity and sessions
Design the reference architecture for a retail digital banking platform on AWS: edge protection, a backend-for-frontend per channel, OIDC sign-in with step-up authentication, short-lived sessions, and the 15-section write-up a design authority expects.
Assumes: .NET 10 LTS · ASP.NET Core 10 · AWS SDK for .NET v4 · CDK v2 (Amazon.CDK.Lib 2.277.0) · Terraform AWS provider v6 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Draw the end-to-end reference architecture of a digital banking platform: edge, API layer, backend-for-frontend (BFF), domain services, data stores and the core banking link.
- Explain why each channel (mobile app, web, third-party providers) gets its own entry point and its own tokens.
- Design customer sign-in with OpenID Connect, MFA and step-up authentication for risky actions, using Amazon Cognito or an external identity provider.
- Choose session and token lifetimes, and say what happens when a device is stolen.
- Implement a step-up authorisation policy in ASP.NET Core 10 that a payment endpoint can require.
- Write the platform as a 15-section architecture, with failure scenarios and compliance touchpoints.
Prerequisites
- How to read and write a banking architecture: the 15-section template used here
- OAuth 2.0, OIDC and JWTs and Cognito user pools
- WAF and Shield and Zero trust and Verified Access
- Container APIs and VPC Link
- Tools: .NET 10 SDK (optional, for the code), AWS CLI v2 with
learn-sandbox(optional)
Why this matters in banking
A digital banking platform is the bank's front door. It is also its most attacked surface, and the place where a design mistake turns into customer harm the same day.
Consider three incidents that real banks have faced in various forms (generalised and fictional here):
- A mobile app talks directly to six internal microservices. A new service ships without the authorisation check. Customers can read each other's data by changing an account id in the URL.
- A session token lives for 30 days and is stored in plain app storage. A customer's lost phone is a standing invitation to move money.
- A marketing banner on the web channel loads a script from a third party. The script reads the page and sends details elsewhere.
Each is a platform architecture failure, not a coding slip. The remedy is structural: one controlled entry per channel, central authentication, short-lived credentials, step-up for risky actions, and an edge layer that blocks abuse before it reaches the services.
The idea in plain language
Think of the platform in four layers.
- Edge. The public face. It terminates TLS, filters abusive traffic and serves static content. In AWS: Amazon CloudFront, AWS WAF, AWS Shield.
- Entry (API) layer. One authenticated door per kind of client. In AWS: Amazon API Gateway, with JWT or Lambda authorisers.
- Backend-for-frontend (BFF). A small service per channel that shapes data for that channel and calls domain services on its behalf. The mobile BFF returns compact payloads; the web BFF may hold the session in a cookie so the browser never sees a token.
- Domain services. Accounts, payments, onboarding, notifications. They know nothing about channels. They trust only calls from the layer above, proven by network path and service identity.
Analogy: a bank branch. The street entrance (edge) has a doorman who turns away trouble. The reception desk (API layer) checks your appointment. Your personal banker (BFF) takes your request, speaks the bank's internal language to the back office (domain services) and brings back an answer in a form you understand. You never walk into the vault.
Why a BFF per channel
| Without BFFs | With a BFF per channel |
|---|---|
| One API serves mobile, web and partners; every change risks all of them | Each channel evolves at its own pace |
| The mobile app must stitch together many calls on a slow network | The mobile BFF aggregates calls and returns one compact response |
| Web tokens are exposed to browser JavaScript | The web BFF keeps tokens server-side and issues an HttpOnly session cookie |
| Authorisation rules are scattered | The BFF enforces channel-specific rules; domain services enforce the data rules |
A third-party-provider (open banking) channel is not a BFF of the customer app. It has its own consent model and certificates; see Open Banking and PSD2-style APIs.
What problem the AWS services solve
| Service | Role in the platform | Limits and sharp edges |
|---|---|---|
| Amazon CloudFront | Global edge cache and TLS termination; hides origins | A request is capped by the origin response timeout (configurable, with a quota ⚠ VERIFY); cache only content that is safe to cache, never account data |
| AWS WAF | Rate limits, managed rule groups, bot control, IP reputation | Rules cost per rule and per request; inspection of large bodies is limited ⚠ VERIFY; tune in count mode first |
| AWS Shield Standard / Advanced | DDoS protection (Standard is automatic and free; Advanced is a paid subscription) | Advanced has a significant monthly commitment ⚠ VERIFY; decide with your security team |
| Amazon API Gateway | Authentication, throttling, request validation, usage metering | REST API integration timeout defaults to 29 seconds, adjustable for Regional APIs under quota rules ⚠ VERIFY; payload limit 10 MB for REST |
| Amazon Cognito user pools | Customer sign-up, sign-in, MFA, token issuing | Customisation of token claims uses Lambda triggers; migrate carefully, as a user pool's attributes cannot all be changed later ⚠ VERIFY |
| Amazon ECS on AWS Fargate | Runs the BFFs and domain services as containers | Cold starts on scale-out are seconds, not milliseconds; plan capacity for peaks |
| Amazon ElastiCache (Valkey) | Server-side session store for the web BFF | A cache may lose data on failure; losing a session means re-login, which is acceptable; losing a payment record is not |
| AWS Secrets Manager / KMS | BFF client secrets, signing keys, encryption | Keys and secrets are separate services; rotation needs planning |
| Amazon DynamoDB / Aurora | Per-service data stores | Each domain owns its own data; shared tables couple teams |
Honest limitation: managed services reduce what you operate, but they do not decide your session lifetimes, your step-up rules or your trust boundaries. Those are design decisions you must write down.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Azure Front Door + WAF | CloudFront + AWS WAF + Shield | Edge and WAF are separate services you attach together; WAF web ACLs for CloudFront live in us-east-1 |
| Azure API Management | API Gateway (plus Lambda authorisers) | Fewer built-in policy transforms than APIM; logic often moves to a BFF or authoriser |
| Microsoft Entra External ID (customer identity) / Azure AD B2C | Amazon Cognito user pools, or an external IdP federated in | Cognito is simpler and cheaper but less configurable; banks often federate an enterprise customer-identity product instead |
| ASP.NET Core cookie sessions with Data Protection keys | ASP.NET Core with ElastiCache session store; keys in KMS or Secrets Manager | Data Protection keys must be shared across containers, or users are logged out on every deploy |
| Azure App Service / Container Apps | ECS Fargate (or App Runner for small cases) | Networking is explicit: subnets, security groups, VPC Link |
| Azure Application Gateway private endpoints | API Gateway VPC Link to an internal load balancer | The ALB or NLB stays private; only API Gateway can reach it |
Architecture
The platform at container level
Security-boundary view
Each box crossing is a trust boundary: TLS plus authentication at the edge, token validation at API Gateway, service identity between BFF and domain service (SigV4 or mTLS, see service-to-service calls), and customer-scoped authorisation inside each domain service.
Step-by-step implementation
This is a design walkthrough with small implementation pieces. Section numbers refer to the 15-section template.
Fix the requirements (sections 1 to 3)
For Harbourline's retail app (fictional targets):
| Quality | Target |
|---|---|
| Availability, sign-in and balance view | 99.95% monthly |
| Latency, account list | p95 under 400 ms from API Gateway to response |
| Session | Access token 15 minutes; refresh up to 8 hours of inactivity ⚠ VERIFY with security policy |
| Step-up | Required for: new payee, payment above GBP 500, change of contact details, card controls |
| Peak | 3,000 requests per second at payday peak |
| Recovery | RTO 15 minutes for sign-in and balance view |
Choose identity (sections 5 and 7)
Two realistic options:
- Cognito user pool as the customer identity provider. Fast to build, integrates with API Gateway JWT authorisers. You customise tokens with Lambda triggers.
- Federated enterprise customer-identity product behind an OIDC connection. More control over risk-based authentication; more to integrate.
Record the decision as an ADR. In both cases, use authorisation code flow with PKCE for the mobile app and a confidential client (secret held server-side in Secrets Manager) for the web BFF. Never put tokens in URLs.
Decide token and session lifetimes (section 7)
| Item | Lifetime | Where it lives | Why |
|---|---|---|---|
| Access token | 15 minutes | Memory only | A stolen token expires quickly |
| Refresh token | Up to 8 hours since last use, rotated on each use | Mobile secure storage (Keychain or Keystore), or server-side for web | Limits the window for a stolen device |
| Web session cookie | Same as refresh; HttpOnly, Secure, SameSite=Strict | Browser | JavaScript cannot read it |
| Step-up proof | 5 minutes | Claim in a fresh token | Fresh proof for a risky action only |
Enable token revocation so sign-out and "lost device" invalidate refresh tokens. State plainly in the document that access tokens already issued stay valid until they expire, which is why they are short.
Put the BFF in front of domain services (sections 4 and 8)
The BFF holds the channel contract (GET /mobile/v1/home returns accounts, recent transactions and alerts in one call). It calls domain services with its own service identity, passing the customer id from the validated token as a signed claim. Domain services re-check that the customer owns the account. Never trust a customer id supplied in the URL.
Protect the edge (section 6 and 7)
Attach an AWS WAF web ACL to the CloudFront distribution: managed rule groups, a rate-based rule per IP on sign-in routes, and a stricter rule for /payments. Start new rules in count mode, review logs, then switch to block. Add security response headers (CSP, HSTS, frame ancestors) at CloudFront.
Write failure scenarios (section 11)
| Failure | Detection | Automatic response | Customer impact | Manual step |
|---|---|---|---|---|
| Identity provider unavailable | Sign-in error rate alarm | Existing sessions continue; new sign-ins show "try again shortly" | Cannot sign in | Incident process; check provider health |
| Core banking slow | BFF latency alarm, circuit breaker open | Show cached balance with an "as at" time; disable payments | Stale balance | Operations engages core team |
| One Availability Zone lost | ALB and Fargate health checks | Tasks reschedule in other AZs | Brief errors | None if capacity headroom is enough |
| Session store failure | ElastiCache failover alarm | Replica promoted; users re-authenticate if data lost | Possible re-login | Review failover |
| Bad BFF deployment | Error budget alarm | Automatic rollback (deployment strategies) | Brief degradation | Post-incident review |
| Credential-stuffing attack | WAF rate rule triggers, sign-in failure spike | Block and challenge; lock out repeatedly failing accounts | Some legitimate users challenged | Fraud team review |
AWS Console instructions
To explore the pieces without building the whole platform:
- Console → Amazon Cognito → User pools → Create user pool. Choose sign-in with email, require MFA, and create an app client of type Single-page / mobile (public) with no client secret.
- App client → Edit: set access token expiration to 15 minutes, enable token revocation, enable Prevent user existence errors.
- Console → WAF & Shield → Web ACLs → Create web ACL. Scope Global (CloudFront) (you must be in us-east-1). Add the AWS managed Core rule set in Count mode, plus a rate-based rule.
- Console → CloudFront → Create distribution, origin an API Gateway stage, and associate the web ACL.
Do not leave any of this running (see Cost and cleanup). All resources must carry the four lab tags.
AWS CLI
# Create a user pool that requires MFA (TOTP). Fictional name; tags follow the course convention.
aws cognito-idp create-user-pool \
--pool-name hl-m14-customers \
--mfa-configuration ON \
--policies 'PasswordPolicy={MinimumLength=12,RequireUppercase=true,RequireLowercase=true,RequireNumbers=true,RequireSymbols=true}' \
--user-pool-tags Project=cea-lab,Lab=m14-l2,Environment=learn,Owner=learner \
--profile learn-sandbox --region us-east-1
# Turn on software-token (TOTP) MFA for the pool; replace the id with the value returned above.
aws cognito-idp set-user-pool-mfa-config \
--user-pool-id <pool-id> \
--mfa-configuration ON \
--software-token-mfa-configuration Enabled=true \
--profile learn-sandbox --region us-east-1
# Create a public app client with short token lifetimes and revocation. No client secret.
aws cognito-idp create-user-pool-client \
--user-pool-id <pool-id> \
--client-name hl-m14-mobile \
--no-generate-secret \
--access-token-validity 15 --id-token-validity 15 --refresh-token-validity 8 \
--token-validity-units AccessToken=minutes,IdToken=minutes,RefreshToken=hours \
--enable-token-revocation \
--prevent-user-existence-errors ENABLED \
--explicit-auth-flows ALLOW_USER_SRP_AUTH ALLOW_REFRESH_TOKEN_AUTH \
--profile learn-sandbox --region us-east-1Why these flags: --mfa-configuration ON makes MFA mandatory; the validity flags implement the lifetime table above; --prevent-user-existence-errors ENABLED makes login failures look identical for unknown and known users, which blocks account enumeration. Verify flag names with aws cognito-idp create-user-pool-client help ⚠ VERIFY.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.Cognito;
using Constructs;
public sealed class CustomerIdentityStack : Stack
{
public CustomerIdentityStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
var pool = new UserPool(this, "Customers", new UserPoolProps
{
UserPoolName = "hl-m14-customers",
SelfSignUpEnabled = false, // onboarding creates users, see the onboarding lesson
SignInAliases = new SignInAliases { Email = true },
Mfa = Mfa.REQUIRED,
MfaSecondFactor = new MfaSecondFactor { Otp = true, Sms = false },
PasswordPolicy = new PasswordPolicy { MinLength = 12, RequireDigits = true, RequireSymbols = true,
RequireLowercase = true, RequireUppercase = true },
AccountRecovery = AccountRecovery.EMAIL_ONLY,
RemovalPolicy = RemovalPolicy.DESTROY, // lab only: production uses RETAIN
});
pool.AddClient("Mobile", new UserPoolClientOptions
{
UserPoolClientName = "hl-m14-mobile",
GenerateSecret = false, // public client: PKCE protects the code
AuthFlows = new AuthFlow { UserSrp = true },
OAuth = new OAuthSettings
{
Flows = new OAuthFlows { AuthorizationCodeGrant = true },
Scopes = [OAuthScope.OPENID, OAuthScope.EMAIL],
CallbackUrls = ["com.example.harbourline://callback"],
},
AccessTokenValidity = Duration.Minutes(15),
IdTokenValidity = Duration.Minutes(15),
RefreshTokenValidity = Duration.Hours(8),
EnableTokenRevocation = true,
PreventUserExistenceErrors = true,
});
}
}Complete code
The BFF must refuse a risky action unless the caller recently proved a second factor. This ASP.NET Core 10 program implements a step-up authorisation policy that reads a claim (auth_age_seconds and mfa are placeholders, see the shortcut note) and returns a ProblemDetails challenge.
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// Authority is the OIDC issuer, e.g. https://cognito-idp.us-east-1.amazonaws.com/<pool-id>
options.Authority = builder.Configuration["Auth:Authority"];
options.Audience = builder.Configuration["Auth:Audience"];
options.MapInboundClaims = false;
options.TokenValidationParameters.ClockSkew = TimeSpan.FromSeconds(30);
});
builder.Services.AddSingleton<IAuthorizationHandler, StepUpHandler>();
builder.Services.AddAuthorizationBuilder()
.AddPolicy("StepUp", p => p.RequireAuthenticatedUser().AddRequirements(new StepUpRequirement(TimeSpan.FromMinutes(5))));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/mobile/v1/home", (ClaimsPrincipal user) =>
Results.Ok(new { customerId = user.FindFirstValue("sub"), message = "accounts would be aggregated here" }))
.RequireAuthorization();
app.MapPost("/mobile/v1/payees", (ClaimsPrincipal user) =>
Results.Accepted(value: new { customerId = user.FindFirstValue("sub"), status = "payee-added" }))
.RequireAuthorization("StepUp");
app.Run();
public sealed record StepUpRequirement(TimeSpan MaxAge) : IAuthorizationRequirement;
public sealed class StepUpHandler(TimeProvider clock) : AuthorizationHandler<StepUpRequirement>
{
// A ctor with TimeProvider lets tests control time; ASP.NET Core registers TimeProvider.System by default.
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, StepUpRequirement requirement)
{
var mfa = context.User.FindFirst("mfa")?.Value == "true";
var authTime = context.User.FindFirst("auth_time")?.Value;
if (mfa && long.TryParse(authTime, out var seconds))
{
var age = clock.GetUtcNow() - DateTimeOffset.FromUnixTimeSeconds(seconds);
if (age <= requirement.MaxAge && age >= TimeSpan.Zero)
{
context.Succeed(requirement);
}
}
// Not calling Fail() lets other handlers run; the endpoint returns 403, which the BFF maps to a step-up challenge.
return Task.CompletedTask;
}
}Code explained line by line
AddJwtBearervalidates the token's signature, issuer, audience and expiry against the identity provider's published keys.Authoritymakes ASP.NET Core download and cache the OIDC metadata.MapInboundClaims = falsekeeps claim names as issued (sub) instead of mapping them to long Microsoft URIs, which avoids confusion when you port logic between services.ClockSkewof 30 seconds is tight on purpose: the default is five minutes, which silently lengthens a 15-minute token.StepUpRequirementcarries the maximum age of the authentication event. TheStepUppolicy combines "authenticated" with this requirement.- The
/homeroute needs only a valid token. The/payeesroute requires theStepUppolicy, so adding a payee demands recent strong authentication. StepUpHandlerreads two claims. It succeeds only when the user did multi-factor authentication and the authentication event is under five minutes old. It never throws on malformed claims; a bad claim simply means "not proven".TimeProvideris injected so a unit test can pass a fake clock, the same technique used in the Module 14 lab.
Security considerations
⚠ Learning shortcut — not for production
The code trusts two claims named mfa and auth_time. Standard OIDC defines auth_time and the authentication context claims acr and amr, but which claims your identity provider actually emits varies by product and configuration ⚠ VERIFY. With Cognito, custom claims are typically added by a pre-token-generation Lambda trigger, and the trigger must derive them from real authentication events, not from client-supplied data. In production, also bind step-up to the specific transaction (for example, the payee being added), so one successful step-up cannot be reused to approve a different action.
- Never trust client-supplied customer ids. The BFF takes the customer id from the validated token and domain services re-check ownership.
- Step-up and transaction signing. For high-value payments, regulations in some jurisdictions require authentication that links to the amount and payee (often called dynamic linking). Confirm the requirement with compliance ⚠ VERIFY.
- Do not log tokens. Log the token's
jtior a hash, never the token. Mask account numbers in logs. - Cookies:
HttpOnly,Secure,SameSite=Strict, and__Host-prefix for the session cookie on the web channel. - CORS: allow only the bank's origins; do not use wildcard with credentials.
- Edge headers: CSP without
unsafe-inline, HSTS with preload decision made by your security team. - Shared responsibility: AWS secures the edge and managed services; you own the WAF rules, identity configuration, token lifetimes and the application's authorisation logic.
Banking use case
Harbourline's retail app has 1.2 million (fictional) customers. On payday the platform sees a peak of 3,000 requests per second, mostly balance views. The design applies the lessons above:
- Balance and transaction views use the cheapest path: valid token, no step-up, BFF aggregation with a short cache of recent balances.
- Adding a payee, changing a phone number or paying above the threshold goes through step-up.
- An attacker running credential stuffing is stopped at the edge by a WAF rate rule and by the identity provider's own lockout logic.
- If core banking slows down, the BFF opens a circuit breaker, shows the last known balance with an "as at" timestamp and disables payments rather than hanging.
The same platform later hosts the flows in customer onboarding, account management and payment processing.
Common mistakes
- One shared API for every channel → slow evolution and wide blast radius → add a BFF per channel.
- Long-lived tokens "for convenience" → a stolen device stays valid for weeks → short access tokens, rotated refresh, revocation.
- Tokens in browser storage → any injected script can read them → web BFF with HttpOnly cookie sessions.
- Authorisation only at the edge → internal calls bypass it → every domain service checks ownership itself.
- Caching authenticated responses at CloudFront → one customer's data served to another → never cache account data at the edge; vary on the auth header only for explicitly safe content.
- WAF in block mode on day one → blocks real customers → count mode, review, then block.
- Forgetting Data Protection keys → every deployment logs users out → share keys across containers.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
401 with invalid_token and IDX10223 | Token expired (or clock drift) | Refresh the token; check host clock sync; keep ClockSkew small but non-zero |
401 with audience error | Access token vs ID token, or wrong Audience | Cognito access tokens carry client_id, not aud; set validation accordingly ⚠ VERIFY |
Step-up endpoint always returns 403 | mfa or auth_time claim missing from token | Check the token's claims at jwt.io style decoders (with fictional users only); fix the trigger |
| Users logged out after each deployment | Data Protection keys not shared | Persist keys in a shared store such as an encrypted S3 object or Secrets Manager |
CloudFront returns 502 for API calls | Origin unreachable or TLS name mismatch | Check origin protocol, certificate name and security groups |
| WAF blocks the mobile app's calls | Managed rule matches a legitimate header or body | Switch the rule to count mode, check sampled requests, add a scoped exception |
API Gateway 504 | Integration timeout (about 29 seconds default for REST APIs) | Reduce downstream latency or use asynchronous patterns ⚠ VERIFY current limit |
Cost and cleanup
This lesson is design-first and free. The optional Cognito user pool is small: Cognito pricing is by monthly active user with a free tier, and a lab pool with a few users costs close to nothing ⚠ VERIFY current tiers. A WAF web ACL and CloudFront distribution do bill (WAF per web ACL, rule and request; CloudFront per request and data), so build them only if you will delete them within the hour.
# Delete the user pool client and pool (replace ids).
aws cognito-idp delete-user-pool-client --user-pool-id <pool-id> --client-id <client-id> \
--profile learn-sandbox --region us-east-1
aws cognito-idp delete-user-pool --user-pool-id <pool-id> --profile learn-sandbox --region us-east-1
# If you created IaC, destroy it.
cdk destroy --all # or: terraform destroy
# Confirm nothing tagged for the course remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--profile learn-sandbox --region us-east-1For a rough monthly estimate in your design document, use the AWS Pricing Calculator with fictional volumes and record each assumption (requests per month, GB transferred, WAF rules, MAU).
Exercises
- 🟢 Guided: write the NFR table and the failure table (sections 3 and 11) for the digital platform, using the examples above as a model. Add one more failure scenario of your own.
- 🟡 Challenge: add a unit test for
StepUpHandlerwith a fakeTimeProvider: a token withauth_timesix minutes old must fail; four minutes old must pass; a futureauth_timemust fail. - 🔴 Live problem: a security review finds that the web channel keeps access tokens in
localStorage. You must move to a BFF cookie session within a sprint with no customer-visible change. Write the migration plan, the rollback plan and the list of what could break (CORS, CSRF, mobile deep links, shared Data Protection keys).
Assignment
Produce a 15-section architecture for the digital banking platform in architecture/digital-platform/ of your portfolio repository: context and container diagrams, the security-boundary diagram, token lifetime table, ADRs for identity provider and BFF-per-channel, and a compliance touchpoints table. Include the step-up handler and its tests.
Solutions
Failure: the WAF managed rules block a new mobile app version because a header looks suspicious.
Detection: a sudden rise in 403 from CloudFront for one app version; WAF sampled requests show the matching rule.
Automatic response: none; WAF is working as configured.
Customer impact: the new version cannot sign in.
Manual step: put the rule in count mode for that path, add a scoped exception, and add a synthetic canary test for each app release in the pipeline.
Why it matters: edge protection is itself a change risk, so the design needs a release check against it.
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Time.Testing; // package: Microsoft.Extensions.TimeProvider.Testing
using Xunit;
public class StepUpHandlerTests
{
private static async Task<bool> Run(long authTimeOffsetSeconds, string mfa = "true")
{
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 11, 18, 12, 0, 0, TimeSpan.Zero));
var claims = new[]
{
new Claim("mfa", mfa),
new Claim("auth_time", clock.GetUtcNow().AddSeconds(authTimeOffsetSeconds).ToUnixTimeSeconds().ToString()),
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "test"));
var requirement = new StepUpRequirement(TimeSpan.FromMinutes(5));
var context = new AuthorizationHandlerContext([requirement], user, null);
await new StepUpHandler(clock).HandleAsync(context);
return context.HasSucceeded;
}
[Fact] public async Task Four_minutes_old_passes() => Assert.True(await Run(-240));
[Fact] public async Task Six_minutes_old_fails() => Assert.False(await Run(-360));
[Fact] public async Task Future_auth_time_fails() => Assert.False(await Run(+60));
[Fact] public async Task Missing_mfa_fails() => Assert.False(await Run(-10, mfa: "false"));
}Why: each test pins one boundary of the rule, and the fake clock removes flakiness. The future-time case matters: a forged or skewed claim must not extend the window.
Knowledge check
Answer: Tokens held in the browser are readable by any script that runs on the page (cross-site scripting). A BFF stores them server-side and issues an HttpOnly cookie that JavaScript cannot read, reducing the damage of an injected script. The BFF must then also defend against cross-site request forgery with SameSite cookies and anti-forgery checks.
Answer: It stops the thief from obtaining new access tokens. It does not invalidate an access token already issued, which stays valid until it expires, which is why access tokens are short (minutes). High-risk actions also need step-up, so a stolen but unlocked session cannot add payees.
Answer: In every domain service, not only at the edge or in the BFF. Anything reachable internally could otherwise bypass the check. The customer id comes from the validated token, never from a URL or body field.
Answer: To see what it would block before blocking real customers. False positives on legitimate banking traffic cost money and trust. Review sampled requests, add scoped exceptions, then switch to block.
Answer: No. It is personalised, sensitive and changes often. Caching risks serving one customer's data to another. Cache static assets and genuinely public content only; use a short-lived application-level cache keyed by customer inside the BFF if needed.
Interview questions
- Why use a BFF instead of one API for all channels? It lets each channel evolve independently, reduces chattiness on mobile, and lets the web channel keep tokens off the browser. The cost is more services to run, so keep each BFF thin and free of business rules.
- How do you design sessions for a banking app? Short access tokens, rotated refresh tokens with an inactivity limit, revocation on sign-out or device loss, secure storage on the device, HttpOnly cookies on the web, and step-up for risky actions. The exact numbers come from the bank's security policy.
- How does step-up authentication work technically? The API checks claims showing a recent strong authentication; if absent, it returns a challenge. The client completes MFA with the identity provider, gets a fresh token and retries. The proof should be time-limited and ideally bound to the transaction.
- What do you put at the edge? TLS termination, WAF with managed and rate rules, DDoS protection, static content caching and security headers. Never cache personalised data.
- How do you stop one team's bug exposing another customer's data? Defence in depth: identity from the token only, ownership checks in each domain service, automated authorisation tests, and logs that make cross-account access detectable.
Certification practice
A bank's mobile app calls an API behind Amazon API Gateway. Security requires that a stolen device cannot be used for long, and that a risky action needs a recent second factor. Which design meets this with the least custom infrastructure?
A. Issue 30-day access tokens so users rarely sign in. B. Use an OIDC identity provider with short-lived access tokens, rotated refresh tokens with revocation, and a step-up check for sensitive operations. C. Store the user's password in the app and sign in on every request. D. Restrict the API to the corporate IP range.
Answer: B. Short tokens limit exposure and revocation handles device loss. A lengthens exposure. C is a severe credential-handling flaw. D is impossible for mobile customers and does not address stolen devices.
A web channel stores JWTs in browser local storage and suffered a cross-site scripting incident. Which change gives the largest reduction in risk?
A. Increase the token lifetime. B. Move to a server-side BFF that keeps tokens and issues an HttpOnly, Secure, SameSite session cookie. C. Encrypt the token with a static key in JavaScript. D. Disable HTTPS for internal calls.
Answer: B. JavaScript cannot read an HttpOnly cookie. A raises risk. C gives no protection because the key is in the page. D weakens security.
A bank wants separate teams to own the mobile and web channels while sharing domain services, and wants a compromise of one channel not to expose the other. Which approach fits best?
A. A single monolithic API with feature flags per channel. B. A BFF per channel in separate workloads, calling shared domain services with per-BFF service identities and least-privilege policies. C. Duplicate all domain services per channel. D. Let each channel call the database directly.
Answer: B. Separate BFFs isolate blast radius, and per-BFF identities allow least privilege. A couples teams. C duplicates data and logic. D bypasses business rules and ownership checks.
Completion checklist
- I can draw the four layers and say what each protects
- I can explain why access tokens are short and refresh tokens are rotated
- I wrote token lifetime and step-up rules as numbers
- I implemented or read the step-up handler and understood its shortcut
- I ran the cleanup steps and confirmed nothing tagged
Project=cea-labis still billing
Key takeaways
- One controlled entry per channel; a thin BFF per channel; domain services that never trust the caller's word about identity.
- Short tokens, revocable refresh tokens and step-up for risky actions beat long sessions.
- Edge protection (CloudFront, WAF, Shield) is part of the design, and a change risk in its own right.
- Authorisation is enforced where the data lives, not only at the front door.
- Document failure scenarios for identity, core banking and edge controls, not just the happy path.
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.
How to read and write a banking architecture
Use the 15-section architecture template, measurable non-functional requirements and architecture decision records to produce a design a bank's design authority can approve, and check your own documents with a small C# linter.
Customer onboarding: KYC/AML integration, secure document upload and consent
Design a customer onboarding architecture on AWS: an orchestrated KYC workflow that calls an identity-verification provider, secure document upload with quarantine and scanning, a manual-review step, consent capture and the data-protection controls a bank's reviewers will ask about.