Volume 9 · Chapter 9 — Enterprise Application Architecture & System Design
Security Architecture Patterns
9.1 Introduction
Security in a distributed enterprise system is not a feature bolted on at the end; it is a cross-cutting property designed into every layer. With services reachable over the network, identity becomes the perimeter, and the patterns that matter are those for proving who is calling (authentication), deciding what they may do (authorization), and protecting data in motion and at rest. This chapter focuses on the concrete standards - OAuth2, OpenID Connect, JWT - and the architectural patterns that secure APIs and microservices.
9.2 Authentication vs Authorization
These are distinct and frequently confused. Authentication (authN) establisheswhoyou are - verifying identity. Authorization (authZ) establisheswhatyou may do - checking permissions. A token can carry an authenticated identity yet still be denied an action by authorization policy. Authorization models range from role-based (RBAC), through policy-based, to attribute-based (ABAC) for fine-grained rules.
9.3 OAuth2 and OpenID Connect
OAuth2 is a framework for delegatedauthorization- it lets a client obtain a token to access resources on a user’s behalf without handling their password. OpenID Connect (OIDC) layersauthenticationon top, adding an ID token that proves who the user is. Together they are the backbone of modern enterprise auth. The Authorization Code flow (with PKCE) is standard for user-facing apps; Client Credentials is used for service-to-service.
sequenceDiagram autonumber participant U as User participant App as Client App participant IdP as Identity Provider (Entra ID) participant API as Resource API U->>App: sign in App->>IdP: authorization request (+ PKCE) IdP->>U: authenticate (MFA) U-->>IdP: credentials IdP-->>App: authorization code App->>IdP: exchange code for tokens IdP-->>App: ID token (who) + access token (scopes) App->>API: call with access token (Bearer) API->>API: validate signature, issuer, audience, expiry, scopes API-->>App: protected resource
9.4 JWT: Structure and Validation
A JSON Web Token has three parts - header, payload (claims), and signature - and is self-contained: the API validates it locally by checking the signature against the issuer’s public key, plus issuer, audience, and expiry, without a database round trip. That statelessness is its strength (scales well) and its weakness (hard to revoke before expiry), which is why access tokens are short-lived and paired with revocable refresh tokens.
// ASP.NET Core validates the JWT on every request: signature + issuer + audience + expiry.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.Authority = "https://login.microsoftonline.com/tenant/v2.0"; // fetches signing keys
o.TokenValidationParameters = new()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = "api://payments",
ValidateLifetime = true // reject expired tokens
};
});
// Authorization policy on top of the authenticated identity.
builder.Services.AddAuthorization(o =>
o.AddPolicy("CanApprove", p => p.RequireClaim("scope", "payments.approve")));
9.5 Securing APIs and Microservices
API security layers authentication enforcement, authorization policies, input validation, rate limiting, and TLS everywhere. In microservices, each service verifies tokens itself (trust no caller by network location), services authenticate to each other with their own identities (mTLS or client-credentials tokens, ideally via managed/workload identity so there are no stored secrets), and a gateway centralizes edge concerns. Secrets live in a vault, never in code or config.
9.6 Zero Trust and Defense in Depth
Zero Trust replaces “trusted internal network” with “never trust, always verify”: every request is authenticated and authorized regardless of origin, least privilege is enforced, and breach is assumed. Combined with defense in depth - identity, network segmentation, encryption, and monitoring layered so no single control is the only barrier - it is the modern posture for enterprise security. Data is encrypted in transit (TLS) and at rest, with keys managed in a vault.
What is the difference between OAuth2 and OpenID Connect?
OAuth2 is a delegatedauthorizationframework: it lets a client obtain an access token to call resources on a user’s behalf without ever handling the user’s credentials, and the token conveys what the client is allowed to do (scopes). By itself OAuth2 does not standardize telling the clientwhothe user is - it was designed for authorization, not authentication. OpenID Connect is a thin identity layer built on top of OAuth2 that adds authentication: alongside the access token, the identity provider issues an ID token (a JWT) that proves the user’s identity and carries identity claims. So the clean way to state it is: OAuth2 gives you an access token todothings, OIDC adds an ID token that tells youwhosigned in. Modern enterprise sign-in uses OIDC (for authentication) and OAuth2 (for API authorization) together, typically via the Authorization Code flow with PKCE.
How does a resource API validate a JWT, and what are the trade-offs of stateless tokens?
The API validates a JWT locally without calling the identity provider per request: it verifies the signature using the issuer’s published public key (fetched and cached from the provider’s metadata), and checks the standard claims - issuer, audience, and expiry - plus any required scopes or roles for the endpoint. Because everything needed is inside the token, this is fast and scales well, which is the big advantage of stateless tokens: no shared session store or database round trip on every call. The trade-off is revocation: since the token is self-contained and trusted until it expires, you cannot easily invalidate a specific token before its expiry. The standard mitigation is to keep access tokens short-lived (minutes) and pair them with a longer-lived but revocable refresh token, so a compromised access token has a small window and the refresh token can be revoked at the provider. For high-security actions you can additionally check a revocation list or introspection endpoint, accepting the extra cost.
How do services authenticate to each other securely in a microservices system?
Service-to-service calls must not be trusted just because they originate inside the network - that is the flaw Zero Trust addresses - so each service proves its identity and each callee verifies it. Two common mechanisms: mutual TLS, where both sides present certificates and verify each other (often provided transparently by a service mesh sidecar), and token-based auth using the OAuth2 client-credentials flow, where the calling service obtains an access token for its own identity and the callee validates it just like a user token. Crucially, the calling service’s credential should be a managed/workload identity issued and rotated by the platform rather than a secret stored in config, which removes the leaked-credential risk. Combined with least-privilege scopes so each service can only call what it needs, and TLS everywhere, this ensures that even an attacker who reaches the internal network cannot call services without a valid, authorized identity.
How do you design security architecture for a large regulated enterprise system?
I design security as a layered, identity-centric property enforced everywhere, aligned to the regulatory requirements from the start. Identity is the foundation: authentication through a central provider (Entra ID) using OIDC with MFA and conditional access, and authorization via least-privilege policies (RBAC, or ABAC where fine-grained rules are needed) evaluated at every service - never trusting network location. Access to APIs uses OAuth2 with short-lived JWTs validated locally, and services authenticate to each other with workload identities and least-privilege scopes rather than stored secrets, with secrets that must exist held in a vault. I apply Zero Trust and defense in depth so a breach of any single layer is contained: network segmentation and private endpoints, encryption in transit and at rest with vault-managed keys, and a gateway centralizing edge protection (auth, rate limiting, WAF). Data is classified so protection matches sensitivity, and everything is auditable - comprehensive logging of access and changes - because regulators require provable controls. Continuous monitoring and threat detection close the loop, and security requirements are baked into the delivery pipeline (scanning, policy) so they are enforced automatically rather than reviewed late. The result is security integrated into every layer and provable to auditors, not a perimeter bolted on at the edge.
Where should authorization decisions be made in a microservices architecture - the gateway or each service?
Both, at different granularities, and this is a deliberate design decision rather than an either/or. The gateway is the right place for coarse-grained, cross-cutting checks: authenticating the caller (validating the token once at the edge), enforcing broad access rules, and applying rate limiting and threat protection - it stops unauthenticated and obviously unauthorized traffic before it reaches internal services. But the gateway must not be the only place, because trusting it alone recreates a soft interior where anything past the edge is implicitly trusted, violating Zero Trust - an attacker who reaches a service directly, or a bug in internal routing, would bypass all authorization. So each service must also validate the token itself and enforce its own fine-grained, domain-specific authorization, because only the service knows its resources and rules (this user may read this account but not approve this payment). The pattern is defense in depth: authenticate and coarsely authorize at the gateway for efficiency and edge protection, then re-verify identity and apply fine-grained authorization at each service for correctness and Zero Trust. Fine-grained business authorization belongs with the service that owns the resource; the gateway handles the broad, cross-cutting layer.
9.7 Banking Enterprise Scenario
A bank secures its platform on an identity-centric, Zero Trust foundation. Customers sign in through OIDC against Entra ID with MFA; the client receives an ID token and a short-lived access token, and every API validates the JWT locally (signature, issuer, audience, expiry, scopes) on each request. Services authenticate to one another with workload identities and least-privilege scopes - no stored secrets - and a gateway handles edge authentication, rate limiting, and WAF, while each service still enforces its own fine-grained authorization (a user may view an account but not approve a transfer). Data is encrypted in transit and at rest with vault-managed keys, access is fully audited for regulators, and continuous monitoring detects threats. Security is layered through every tier, not perimeter-only.
Chapter Revision Notes
- Authentication proves who you are; authorization decides what you may do.
- OAuth2 = delegated authorization; OIDC adds authentication (ID token) on top.
- JWTs are validated locally (signature/issuer/audience/expiry) - stateless but hard to revoke, so keep them short-lived.
- Services verify tokens themselves and authenticate with workload identities, not network trust.
- Apply Zero Trust and defense in depth; encrypt in transit and at rest; secrets in a vault.
- Coarse authorization at the gateway, fine-grained authorization at each service.