Security for Architects
- Separate authentication from authorization and choose the right OAuth 2.0 / OIDC flow for web, mobile and service-to-service clients
- Validate JWTs safely and decide between server-side sessions and self-contained tokens for a banking app
- Design service identity with mTLS and SPIFFE, and authorization with RBAC, ABAC and maker-checker
- Protect data with TLS, envelope encryption, KMS/HSM and tokenization, and manage secrets without static credentials
- Apply the OWASP API Security Top 10, zero-trust principles and STRIDE to a money-transfer API
TL;DR
- Authentication proves who the caller is; authorization decides what they may do to this specific object. Most real API breaches are authorization failures (OWASP API1: broken object-level authorization).
- Use Authorization Code + PKCE for any app with a user (web, SPA, mobile); Client Credentials (ideally with mTLS or private-key JWT) for service-to-service. Implicit and password grants are deprecated. OIDC adds an ID token that tells the client who logged in; APIs consume access tokens.
- JWT pitfalls: accepting
alg: noneor algorithm confusion, skippingiss/aud/expchecks, fetching keys from URLs in the token, long-lived tokens you can't revoke, and sensitive data in an unencrypted payload. - Service identity: mTLS with short-lived certificates issued per workload (SPIFFE/SPIRE or a service mesh), then authorize on that identity. Network location is not identity — that is the core of zero trust.
- Encrypt in transit (TLS everywhere, including inside the VPC) and at rest; use envelope encryption (data keys wrapped by a KMS/HSM key) for sensitive fields, and tokenize card numbers to shrink PCI scope.
- Secrets come from a manager (Vault, cloud secret managers) with rotation and, ideally, dynamic short-lived credentials — never from code, images or logs.
- Threat model each design with STRIDE across its trust boundaries before you build it.
Why it matters
Banks and e-commerce platforms are prime targets: they hold money, card data and identity data, and their APIs are reachable from the internet and from partners. The typical breach is not exotic cryptography failing; it is an API that returns another customer's account when you change the ID in the URL, a JWT accepted without checking its audience, a long-lived database password in a config repo, or a card number written to a log.
Regulation raises the stakes: PCI DSS for card data, data-protection laws for personal data, and banking regulators who expect strong customer authentication, segregation of duties and auditable access. As an architect you are expected to make security a property of the design — trust boundaries, identities, keys and authorization models — not a checklist bolted on before go-live. Interviewers probe exactly these decisions.
Core concepts
Authentication vs authorization
- Authentication (authn): verify identity — password + second factor, passkey/WebAuthn, device binding, client certificate.
- Authorization (authz): decide whether this identity may perform this action on this resource, now. It must be enforced on the server, for every request, at the object level.
Banking adds step-up authentication: a login session may view balances, but a new payee or a large transfer requires a fresh strong factor. Under the EU's PSD2, strong customer authentication combines two of knowledge, possession and inherence, and for payments the authentication must be dynamically linked to the amount and payee.
OAuth 2.0 and OIDC
OAuth 2.0 is a delegated authorization framework: a client obtains an access token from an authorization server to call a resource server (API) on behalf of a resource owner (user) or itself. OpenID Connect (OIDC) layers authentication on top: an ID token (a JWT) tells the client who the user is.
Authorization Code + PKCE — the default for user-facing apps:
PKCE (Proof Key for Code Exchange) binds the code to the client instance that started the flow, so an intercepted authorization code is useless without the verifier. Current guidance (the OAuth 2.0 Security Best Current Practice and the OAuth 2.1 draft) recommends PKCE for all clients, including confidential ones.
Client Credentials — service-to-service with no user: the service authenticates to the authorization server (client secret, or better a private-key JWT or mTLS) and receives a token with scopes such as ledger.post. Prefer short token lifetimes and per-service clients.
Other notes:
- Refresh tokens should be rotated on use and revoked on logout or suspicious reuse.
- Implicit and Resource Owner Password Credentials grants are deprecated — don't design new systems with them.
- Scopes are coarse permissions granted to the client (
payments:write); they do not replace object-level checks ("is this your account?"). - Open banking profiles such as OpenID's FAPI tighten all of this: pushed authorization requests (PAR), sender-constrained tokens (mTLS-bound or DPoP), and stricter client authentication.
JWT pitfalls
A JWT is base64url(header).base64url(payload).signature. It is signed, not encrypted — anyone holding it can read the payload.
alg: noneand algorithm confusion. Libraries that trust the header'salgcan be tricked into accepting unsigned tokens, or into verifying an RS256-issued token as HS256 using the public key as the HMAC secret. Pin the allowed algorithms.- Missing claim checks. Validate
iss(your issuer),aud(this API),exp/nbf(with small leeway for clock skew), and the token type. A token minted for another API in your company must not work on the payments API. - Key sourcing. Fetch verification keys from your issuer's JWKS endpoint (cached, refreshed by
kid). Never trustjku,x5uor embeddedjwkheaders that point to keys chosen by the token's author. - Revocation. A self-contained token is valid until it expires. Keep access tokens short (minutes), use refresh tokens for longevity, and use opaque tokens with introspection — or a denylist — where immediate revocation is required (e.g., a bank locking a compromised session).
- Payload contents. No PII beyond what is needed, never secrets; use JWE if the payload must be confidential.
- Storage in browsers. Tokens in
localStorageare readable by any XSS. For SPAs, the backend-for-frontend (BFF) pattern keeps tokens server-side and gives the browser anHttpOnly,Secure,SameSitesession cookie.
package auth
import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
type Claims struct {
Scope string `json:"scope"`
jwt.RegisteredClaims
}
type Verifier struct {
KeyByID func(kid string) (any, error) // backed by the issuer's JWKS, cached
Issuer string
Audience string
}
func (v *Verifier) Verify(raw string) (*Claims, error) {
claims := &Claims{}
_, err := jwt.ParseWithClaims(raw, claims,
func(t *jwt.Token) (any, error) {
kid, _ := t.Header["kid"].(string)
return v.KeyByID(kid) // never keys referenced by the token itself
},
jwt.WithValidMethods([]string{"RS256", "ES256"}), // blocks none and HS256 confusion
jwt.WithIssuer(v.Issuer),
jwt.WithAudience(v.Audience),
jwt.WithExpirationRequired(),
jwt.WithLeeway(30*time.Second),
)
if err != nil {
return nil, fmt.Errorf("verify token: %w", err)
}
return claims, nil
}
Authentication is only half the job; the handler must still check the object:
func (h *Handler) GetAccount(w http.ResponseWriter, r *http.Request) {
claims := ClaimsFrom(r.Context())
acct, err := h.accounts.Get(r.Context(), r.PathValue("id"))
if err != nil || acct.OwnerID != claims.Subject { // object-level authorization (OWASP API1)
http.NotFound(w, r) // don't reveal whether the account exists
return
}
writeJSON(w, acct)
}
Sessions vs tokens
| Aspect | Server-side session (cookie) | Self-contained token (JWT) |
|---|---|---|
| State | Session store (Redis/DB) | In the token |
| Revocation | Immediate (delete session) | Hard until expiry; needs denylist or short TTL |
| Scaling | Store lookup per request | No lookup; verify signature |
| Browser security | HttpOnly + SameSite cookies resist XSS theft; need CSRF defence | If stored in JS-accessible storage, exposed to XSS |
| Best for | Banking web apps, BFFs, anything needing instant logout and idle timeouts | Service-to-service, APIs consumed by many resource servers, mobile with short-lived tokens |
Many banks combine them: the browser holds a session cookie with a BFF; the BFF holds short-lived access tokens to call internal APIs; idle and absolute session timeouts are enforced server-side.
mTLS and service identity
Inside your platform, "it came from the internal network" is not authentication. Each workload should have a cryptographic identity and every call should be authenticated and authorized.
- mTLS: both client and server present certificates; each verifies the other's chain and identity.
- SPIFFE standardizes the identity: a URI like
spiffe://bank.example/ns/payments/sa/ledger-writer, carried in an SVID (an X.509 certificate or JWT). SPIRE (or a service mesh such as Istio or Linkerd) attests workloads (Kubernetes service account, node identity) and issues short-lived certificates, rotating them automatically — often hourly or faster. - Authorize on identity: the ledger accepts
Postonly from the payment and transfer services' identities; the notification service can read nothing from the ledger. Mesh authorization policies or a policy engine enforce this.
Authorization models
- RBAC: permissions grouped into roles (
teller,branch_supervisor,ops_reconciler). Simple and auditable; becomes "role explosion" when you encode context into roles. - ABAC: decisions on attributes of subject, resource, action and environment — "a teller may approve transfers up to $10,000 for accounts in their own branch during business hours from a managed device". Policy engines such as OPA (Rego) or Cedar externalize these rules.
- ReBAC: relationship-based (Google's Zanzibar model; OpenFGA, SpiceDB) — "user can view invoice if they are a member of the merchant that owns it". Natural for marketplaces and multi-tenant B2B.
- Maker-checker (four-eyes): for high-risk operations (manual ledger adjustments, limit increases, payee whitelisting for corporate accounts), one person initiates and a different authorized person approves. Enforce "approver ≠ maker" in the service, and audit both.
- Least privilege and segregation of duties apply to engineers too: production database access is just-in-time, approved and recorded.
Encryption in transit and at rest
- In transit: TLS 1.2+ (prefer 1.3) on every hop, including internal service calls and database connections; HSTS for web; automated certificate issuance and rotation. See TLS & HTTPS.
- At rest, layered:
- Disk/volume encryption protects against stolen media and decommissioned disks — but anyone with database access still reads plaintext.
- Database-level encryption (TDE) — similar threat coverage, transparent to apps.
- Application-level (field-level) encryption for the most sensitive fields (card data, national IDs, account credentials): the database only ever stores ciphertext, and decryption requires both data access and key access.
Envelope encryption, KMS and HSM
Encrypting every record directly with a central key would send all data through the key service. Envelope encryption splits the job:
- The data encryption key (DEK) encrypts the data locally (fast); the key encryption key (KEK) never leaves the KMS/HSM.
- Rotation of the KEK only re-wraps DEKs; data does not need re-encryption.
- Access control and audit move to the key: every unwrap is an authorized, logged KMS call — a powerful detection signal.
- Crypto-shredding: deleting a customer's DEK makes their data unrecoverable, which helps with data-deletion obligations.
- KMS (AWS KMS, Google Cloud KMS, Azure Key Vault) is a managed service backed by HSMs; HSMs are tamper-resistant devices validated to standards such as FIPS 140-2/140-3. Banks also use dedicated payment HSMs for PIN translation and verification, card verification values and EMV cryptogram checks — operations that card schemes require to happen inside certified hardware.
Tokenization
Tokenization replaces a sensitive value (a PAN) with a non-sensitive surrogate. Only the token vault can map token → PAN.
- Systems that only see tokens (order service, analytics, customer support tools) can fall outside much of the PCI DSS cardholder data environment — a large cost and risk reduction.
- Flavors: PSP tokens (your PSP stores the card; you hold a token usable only with that PSP), network tokens issued by card schemes (survive card reissue, can improve approval rates), and an internal vault (when you must route to several acquirers).
- Tokens can be format-preserving (same length, last four digits kept) for legacy systems — but then make sure they can't be confused with real PANs.
- Tokenization is not encryption: there is no key that "decrypts" a token; there is a vault lookup with strict access control.
See Payments & Card Flows and Compliance.
Secrets management
- Never in source code, container images, CI logs or plain environment files in repos. Scan for them (pre-commit and CI).
- Use a secret manager: HashiCorp Vault, AWS Secrets Manager, Google Secret Manager, Azure Key Vault. Access by workload identity, not a bootstrap password.
- Prefer dynamic secrets: Vault's database secrets engine creates a short-lived database user per service instance with a lease, revoked automatically. A leaked credential expires in hours, not years.
- Workload identity federation (Kubernetes service accounts mapped to cloud IAM roles) removes long-lived cloud keys entirely.
- Vault's transit engine offers encryption-as-a-service (the app sends plaintext, gets ciphertext; keys never leave Vault) — an alternative to client-side envelope encryption.
- Rotate regularly and on every suspected exposure; design apps to reload credentials without restart.
OWASP API Security Top 10 (2023) through a banking/e-commerce lens
| ID | Risk | Example |
|---|---|---|
| API1 | Broken Object Level Authorization | GET /accounts/8812 returns another customer's account |
| API2 | Broken Authentication | Weak token validation; no rate limit on OTP verification |
| API3 | Broken Object Property Level Authorization | PATCH /me accepts kyc_status or daily_limit fields (mass assignment); responses leak internal fields |
| API4 | Unrestricted Resource Consumption | Unbounded statement export; no pagination limits; SMS OTP cost abuse |
| API5 | Broken Function Level Authorization | A customer token can call POST /admin/refunds |
| API6 | Unrestricted Access to Sensitive Business Flows | Bots buying all flash-sale stock; card-testing via small authorizations |
| API7 | Server Side Request Forgery | Merchant-supplied webhook URL pointing at the cloud metadata endpoint |
| API8 | Security Misconfiguration | Verbose errors with stack traces; permissive CORS; TLS off internally |
| API9 | Improper Inventory Management | Old v1 endpoint without the new authorization checks still live |
| API10 | Unsafe Consumption of APIs | Trusting a partner bank's or PSP's response without validation or signature checks |
Zero trust
NIST SP 800-207 summarizes the idea: no implicit trust based on network location. In practice:
- Authenticate and authorize every request (users, devices and workloads), using strong identities (mTLS, OIDC).
- Least privilege, per-request authorization, short-lived credentials.
- Micro-segmentation: default-deny network policies between services; allow only declared flows.
- Continuous evaluation: device posture, risk signals (new device, impossible travel) feeding step-up or denial.
- Assume breach: encrypt internally, log and monitor access, limit blast radius.
Threat modeling with STRIDE
STRIDE (from Microsoft) is a checklist of threat categories to apply to each element and data flow crossing a trust boundary:
| Threat | Property violated | Transfer API example | Mitigations |
|---|---|---|---|
| Spoofing | Authentication | Stolen session token used from another device | MFA, device binding, short tokens, sender-constrained tokens |
| Tampering | Integrity | Amount changed between app and server, or in a message to the switch | TLS, server-side recomputation, message signing/MAC, dynamic linking of auth to amount and payee |
| Repudiation | Non-repudiation | Customer denies initiating a transfer | Signed transaction confirmation, audit trail with device and auth context |
| Information disclosure | Confidentiality | Transfer history of other users via BOLA; PAN in logs | Object-level authz, field encryption, redaction, least privilege |
| Denial of service | Availability | OTP or transfer endpoint flooded | Rate limiting, bot detection, load shedding, quotas |
| Elevation of privilege | Authorization | Customer calls an operator-only reversal endpoint | Function-level authz, separate admin plane, maker-checker |
Do this during design reviews, record threats and decisions alongside your ADRs (see Documenting Architecture), and revisit when trust boundaries change.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Server-side sessions | Instant revocation, idle timeouts, cookies resist XSS theft | Session store dependency; CSRF to handle | Customer-facing banking web, BFF pattern |
| Short-lived JWT access tokens | Stateless verification across many APIs | Revocation lag; validation pitfalls | Service and API ecosystems; mobile with refresh rotation |
| Opaque tokens + introspection | Immediate revocation, no payload exposure | Introspection call per request (cacheable) | High-risk APIs needing instant kill switches |
| mTLS via service mesh | Uniform identity and encryption, little app code | Mesh complexity and resource overhead | Many services, Kubernetes platforms |
| App-level mTLS / SPIFFE libraries | Fine control, no sidecars | Per-language implementation effort | Few services or performance-sensitive paths |
| RBAC | Simple, auditable | Role explosion with contextual rules | Staff permissions with stable job functions |
| ABAC / policy engine | Expressive, contextual, centralized | Policy testing and performance; harder audits | Limits, branches, amounts, risk-based rules |
| Envelope encryption with KMS | Strong key control, audit, rotation, crypto-shredding | KMS latency and cost (cache DEKs carefully) | Sensitive fields: PAN, national ID, account secrets |
| Tokenization | Removes sensitive data from most systems; shrinks PCI scope | Vault becomes critical; detokenization must be tightly controlled | Card data, bank account numbers shared widely |
In practice
- Token lifetimes (rough, common practice): access tokens ≈ 5–15 minutes; refresh tokens hours to days with rotation; banking web sessions with idle timeouts of a few minutes and absolute limits.
- Gateway responsibilities: TLS termination (re-encrypt to backends), token validation, coarse scope checks, rate limits and WAF rules. Object-level and business authorization stay in the service that owns the data.
- Webhooks: sign outgoing webhooks (HMAC with a per-merchant secret plus timestamp to stop replays); verify incoming PSP webhooks the same way; restrict outbound webhook destinations to prevent SSRF.
- Key hierarchy: separate keys per environment, per data class and ideally per tenant; restrict who and what can call
Decrypt; alert on unusual decrypt volume. - Security in the pipeline: dependency and image scanning, secret scanning, SAST, infrastructure-as-code policy checks, signed artifacts.
- Audit everything sensitive: logins, step-ups, payee changes, limit changes, detokenization calls, admin actions (see Observability & SLOs).
Common pitfalls
- Authorization only at the gateway. Symptom: any authenticated customer can read any account by changing an ID (BOLA).
- Trusting the JWT header. Symptom: forged tokens accepted (
alg: none, HS256 with the public key, attacker-hostedjku). - Missing
audcheck. Symptom: a token for the low-risk loyalty API works on the payments API. - Mass assignment. Symptom: a customer sets their own
daily_limitorrolevia a profile update. - Long-lived static credentials. Symptom: a database password from a 2019 config leak still works.
- "Internal" means trusted. Symptom: one compromised pod reaches every database because network policies allow all east-west traffic.
- Encrypting at rest and calling it done. Disk encryption does nothing against SQL injection or a stolen app credential.
- Card data in logs, traces or analytics. Symptom: the entire logging platform falls into PCI scope.
Interview angle
- Typical prompts: "How do you secure the transfer API?" "Mobile app login for a bank — which OAuth flow?" "How do services authenticate to each other?" "How do you store card numbers?" "Walk me through a threat model."
- Strong answer: OIDC with Authorization Code + PKCE (BFF for web), MFA and step-up for risky actions with dynamic linking; short-lived tokens with strict validation; object- and function-level authorization in services; mTLS with SPIFFE identities and default-deny policies; TLS everywhere; tokenization of PANs via PSP/network tokens or a vault; envelope encryption with KMS for other sensitive fields; Vault dynamic secrets; audit trail; STRIDE across trust boundaries; OWASP API Top 10 checks in review.
- Follow-ups: "How do you revoke a JWT?" "What's the difference between an ID token and an access token?" "Why PKCE if you already have a client secret?" "Who can decrypt the data and how would you know?" "What's in PCI scope?"
- Red flags: using the ID token to call APIs; "the gateway handles security"; storing tokens in
localStoragefor a banking SPA without discussing XSS; long-lived API keys shared across services; "we encrypt the disk" as the only data-protection answer.
Self-check
1. What's the difference between an ID token and an access token, and which one should an API accept?
The ID token is an OIDC artifact for the client: it tells the client who authenticated, with the client as its audience. The access token is for resource servers: it carries the authorization granted (scopes, subject) with the API as its audience. APIs must accept access tokens with their own audience, never ID tokens.
2. What attack does PKCE prevent, and how?
Authorization code interception: a malicious app or a leaked redirect captures the code and exchanges it for tokens. With PKCE, the client sends a hash of a random verifier when starting the flow and must present the verifier when redeeming the code; an attacker who only has the code cannot produce the verifier.
3. List four checks a resource server must make on a JWT access token.
Signature with a key from the trusted issuer's JWKS, using a pinned algorithm list; iss equals the expected issuer; aud includes this API; exp and nbf are valid within a small leeway. Then authorization checks: scopes for the operation, and object-level ownership for the specific resource.
4. Explain envelope encryption and two operational benefits.
Data is encrypted locally with a data key (DEK); the DEK is encrypted ("wrapped") by a key-encryption key held in a KMS/HSM and stored next to the ciphertext. To read, the service asks the KMS to unwrap the DEK. Benefits: KEK rotation only re-wraps DEKs without re-encrypting data; every unwrap is an authorized, audited KMS call; deleting a DEK crypto-shreds the data.
5. How does tokenization reduce PCI DSS scope, and what becomes critical?
Systems that store or process only tokens never see the PAN, so much of the platform can fall outside the cardholder data environment. The token vault (or the PSP holding the cards) and any detokenization path become the critical, tightly controlled components — they need strict access control, auditing and HSM-backed protection.
6. Scenario: your marketplace's GET /orders/{id} returns any order to any logged-in user. Which OWASP API risk is this and how do you fix it systematically?
API1, Broken Object Level Authorization. Enforce ownership checks in the service for every object access — ideally through a shared authorization helper or policy engine (e.g., "order.buyer_id equals subject, or subject is a member of the seller"), return 404 for non-owned objects, add tests that call each endpoint with another user's IDs, and flag new endpoints without authorization in code review.
7. Apply STRIDE to the link between your transfer service and an interbank switch.
Spoofing: mutual TLS and signed messages so neither side can be impersonated. Tampering: message signatures or MACs over amount and accounts. Repudiation: signed, logged messages with sequence numbers. Information disclosure: TLS and minimal data. Denial of service: rate limits, queues, circuit breakers and timeouts. Elevation of privilege: separate credentials per message type and least-privilege access to the switch connection.
Exercise
Threat-model and harden a transfer API:
- Draw the data-flow diagram for "customer transfers money to a new payee" (mobile app, gateway, auth server, transfer service, ledger, audit store, interbank switch) with trust boundaries.
- Apply STRIDE to each boundary crossing; list at least ten threats with mitigations and an owner.
- Implement in Go: JWT verification with the
Verifierabove against a local Keycloak or similar OIDC server; object-level authorization onGET /accounts/{id}; step-up requirement (anacroramrclaim) forPOST /payees. - Add envelope encryption for the payee account number using a local KMS emulator or Vault's transit engine, and audit every decrypt.
- Write negative tests:
alg: nonetoken, HS256-signed token using the public key, wrongaud, expired token, another user's account ID, mass-assignment attempt ondaily_limit.
Done when: every negative test is rejected with the right status code, the STRIDE table has an owner per mitigation, and you can explain which parts of the system would be in PCI scope if payees were cards instead of bank accounts.
Further reading
- RFC 6749 (OAuth 2.0), RFC 7636 (PKCE), RFC 9700 (OAuth 2.0 Security Best Current Practice), and the OAuth 2.1 draft.
- OpenID Connect Core 1.0 and the OpenID FAPI 2.0 Security Profile.
- RFC 8725, "JSON Web Token Best Current Practices".
- OWASP API Security Top 10 (2023).
- NIST SP 800-207, "Zero Trust Architecture".
- SPIFFE documentation.
- Adam Shostack, Threat Modeling: Designing for Security (Wiley).
- Neil Madden, API Security in Action (Manning).
- PCI Security Standards Council, PCI DSS v4.0, and its tokenization guidance.
- HashiCorp Vault documentation: dynamic secrets and the transit secrets engine.
Related
- TLS & HTTPS — the transport security everything else depends on.
- Compliance: PCI DSS, KYC/AML, Data Protection — regulatory drivers for these controls.
- Payments & Card Flows — where tokens, HSMs and PCI scope show up.
- Fraud & Risk Systems — risk signals that drive step-up and denial.
- Proxies, Load Balancers & API Gateways — gateway responsibilities vs service responsibilities.
- Observability & SLOs — audit logging and access monitoring.
- Rate Limiting — defending against resource-consumption and business-flow abuse.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).