Security & Identity
Application Security Architecture: Threat Modelling and Design Principles
Intermediate9 min readReviewed by Mariem Ouled on Updated
Security that is bolted on late is expensive and incomplete. This guide shows how to treat security as an architectural property: draw the system as data flows and trust boundaries, enumerate threats with STRIDE, apply the classic protection principles, decide which layer enforces each control, and fold the whole practice into the delivery pipeline.
What you will learn
- Draw a data-flow diagram with trust boundaries and use it to reason about attack surface
- Enumerate and rank threats with STRIDE and turn each one into a concrete control
- Apply least privilege, defence in depth, complete mediation, fail-secure and secure defaults to real designs
- Choose the correct layer for authentication, authorization and input validation
- Manage application secrets without ever placing them in source control
- Embed security activities into a delivery pipeline rather than a pre-release audit
Almost every serious breach traces back to a decision, not a typo: a service that was given database credentials it never needed, an internal endpoint everyone assumed was unreachable, an integration that trusted an identifier supplied by the caller. Those are architecture problems, and no amount of careful coding downstream fully compensates for them. Designing security in means asking, while the boxes and arrows are still cheap to move, who can talk to what, what they are allowed to do, and what happens when one of the boxes is under an attacker's control.
This guide is about that design work. It covers how to model a system so that threats become visible, the small set of principles that have survived fifty years of practice, where in a layered application each kind of control belongs, how to handle secrets, and how to keep the whole thing running as part of normal delivery instead of a pre-release scramble. The specific risk categories are catalogued in the OWASP Top 10 guide; here we are one level up, deciding the shape of the system that makes those risks unlikely.
Security is a property of the design
Functional requirements describe what the system should do. Security requirements describe what it must never do, no matter who is asking — and negative requirements cannot be tested exhaustively, which is why they have to be structural. "The reporting service cannot read customer payment details" is a strong statement when the reporting service holds no credentials that reach that table; it is a weak statement when it is a code review convention.
Three architectural questions carry most of the weight:
- What are the assets? Personal data, money movement, credentials, audit trails, availability of a critical path. Rank them, because you cannot protect everything equally.
- Where are the trust boundaries? Every point where data crosses from a place you control to one you do not — or between two components with different privilege — is a boundary that needs authentication, authorization and validation.
- What is the blast radius? If one component is fully compromised, what does the attacker reach? A design that answers "everything" needs work regardless of how good its input handling is.
Threat modelling with data flows and STRIDE
A useful threat model starts with a diagram anyone on the team could draw: external actors, processes, data stores, the flows between them, and dotted lines for the trust boundaries. Detail is the enemy — one page, the level of "the browser talks to the API gateway, which calls the order service, which writes to the orders database and publishes an event".
[Browser] --https--> | TB1 | [API gateway] --mTLS--> [Order service] --TLS--> (Orders DB)
| |
v v
[Identity provider] | TB2 | [Payment provider]
TB1 internet / platform boundary — untrusted input, session establishment
TB2 organisation / third party — outbound secrets, response we do not control
Then walk each element and each flow through STRIDE, a mnemonic that maps threat categories onto the property each one violates:
| Threat | Property lost | Typical control |
|---|---|---|
| Spoofing | Authenticity | Strong authentication of users and of services (mutual TLS, signed tokens) |
| Tampering | Integrity | Signatures, integrity-protected transport, server-side validation, immutable audit records |
| Repudiation | Non-repudiation | Append-only logs with reliable identity, signed transactions |
| Information disclosure | Confidentiality | Encryption in transit and at rest, minimisation, careful error messages |
| Denial of service | Availability | Quotas, rate limits, timeouts, bulkheads, resource caps on parsing |
| Elevation of privilege | Authorization | Least privilege, complete mediation, resource-level checks |
Record each finding as a one-line risk with the control that answers it, an owner and a decision. Ranking by likelihood and impact is enough; elaborate scoring rarely changes what a team does next.
- id: "TM-014"
element: "Order service -> Payment provider"
threat: "Information disclosure"
description: "API key for the payment provider is read from an environment variable and printed by the outbound HTTP logger."
likelihood: "medium"
impact: "high"
control: "Redact Authorization headers in the client interceptor; move the key to the secret manager with 90-day rotation."
status: "accepted-fix"
owner: "payments"
Alongside the model, write abuse cases next to the user stories they invert. If the story is "a customer downloads their invoice", the abuse case is "a customer downloads someone else's invoice by changing the identifier in the URL", and it becomes a test. Teams that add one abuse case per meaningful story catch most access-control defects before they exist.
The principles that keep paying off
Least privilege. Every identity — human, service, batch job — gets the narrowest set of permissions that lets it do its work, and no more. In practice this means separate database users per service with grants limited to the tables they touch, cloud roles scoped to specific resources, and containers that do not run as root. It also means privileges expire: a temporary elevation that is never revoked is the same as a permanent one.
Defence in depth. Assume any single control will fail. A parameterised query, a database account without DROP rights and an alert on unusual query volume defend the same asset by different mechanisms.
Complete mediation. Every access to every protected object is checked, every time, on the server. Caching an authorization decision for the duration of a session is how "the user was an admin when they logged in" survives their demotion.
Fail secure. When something goes wrong — the policy service times out, a claim is missing, a certificate cannot be validated — the safe outcome is denial. This is easy to get backwards in code that treats an exception as "unknown, therefore allow".
public boolean canView(User user, Document doc) {
try {
return policyEngine.evaluate(user, "document:read", doc);
} catch (PolicyUnavailableException e) {
log.warn("policy engine unavailable, denying document {}", doc.id(), e);
return false; // deny on failure, never "return true" to keep the page working
}
}
Secure defaults. The out-of-the-box state should be the safe one: registration closed, debug endpoints off, TLS required, sample accounts absent. Anyone who needs something looser opts in explicitly and leaves a trace.
Minimise the attack surface. Every exposed endpoint, enabled feature flag, installed package and open port is something to defend. Removing an unused admin console is a stronger control than protecting it well.
Separation of duties. The person or pipeline that writes a change should not be the only one able to approve and deploy it, and the service that issues credits should not also approve them.
Do not rely on obscurity. Assume the attacker has read your source and your documentation. Secrets are keys and tokens, not URLs and schema names.
Where each control belongs
A recurring design mistake is enforcing a rule in a layer that can be bypassed. Place controls by asking what could reach the operation if the layer above were skipped entirely.
| Concern | Where it belongs | Why |
|---|---|---|
| Transport encryption, rate limiting, coarse routing rules | Edge / gateway | Cheap to apply uniformly; see API management and gateways |
| Authentication of the caller | Edge for identity, re-verified in each service | An internal caller must still prove who it is |
| Coarse authorization (roles, scopes) | Framework filter or interceptor | Applies to every route by default |
| Resource-level authorization ("is this your order?") | Domain or application service | Only that layer knows the ownership rule |
| Syntactic input validation | Boundary, on the server | Reject impossible input early and cheaply |
| Business rule validation ("balance cannot go negative") | Domain model | It is a domain invariant, not an input problem |
| Referential and uniqueness integrity | Database constraints | The last line that no code path can skip |
| Output encoding | View/rendering layer | Encoding depends on the context it lands in |
Client-side validation is a usability feature and nothing more. In a distributed system this table applies per service: in a microservices architecture, the gateway authenticates the end user and each service independently verifies the token and applies its own authorization, because a network position is not a permission. That is the practical core of zero trust as described in NIST SP 800-207.
For the servlet-based implementation of these layers — filter chains, method-level checks and stateless token validation — see Spring Security basics.
Secrets are architecture too
A secret in a repository is compromised from the moment it is pushed, and rewriting history does not un-leak it; the credential must be rotated. The design goal is that no long-lived secret is ever written down by a human.
- Prefer workload identity to shared secrets. Cloud platforms can issue short-lived credentials to a running instance based on its identity, removing the static key entirely.
- Store what remains in a secret manager, injected at runtime as an environment variable or a mounted file, never baked into an image or a configuration file that ships with the build.
- Rotate on a schedule and after every suspicion, and design the application to pick up a new value without a rebuild.
- Separate secrets per environment, so a leaked test key is worthless in production.
- Scan for secrets in the pipeline and in pre-commit hooks, and treat every hit as an incident, not a code-review nit.
- Encrypt sensitive data at rest with keys the application does not hold outright, using a key management service so that a stolen database backup is not a stolen dataset.
Security in the delivery pipeline
Shifting left means the pipeline enforces what the design decided, so that security findings arrive while the change is still in someone's head. A practical delivery pipeline runs, roughly in this order: secret scanning and dependency checks on every commit; static analysis tuned to a low false-positive rate so developers keep trusting it; container and base-image scanning at build; infrastructure-as-code policy checks; a dynamic scan against a deployed test environment; and signed artefacts with provenance so what runs in production is demonstrably what was built.
stages:
- build # unit tests, SAST, secret scan, SBOM generation
- package # container build, image scan, sign the artefact
- verify # deploy to ephemeral env, DAST, authorization test suite
- release # policy gate: no critical findings, provenance verified
Two habits matter more than the tool choice. First, fail the build only on findings the team has agreed are unacceptable, and track the rest with a deadline — a pipeline that always fails teaches people to bypass it. Second, write regression tests for every security defect you fix, especially authorization ones; those are ordinary tests that assert a request returns 403, and they are the cheapest protection against the same bug returning.
Common mistakes
- Modelling only the happy path. The diagram shows the browser and the API, and omits the admin tool, the nightly export and the support engineer's read access — which is where the interesting privileges live.
- Treating the internal network as trusted. Once one service is compromised, a flat, unauthenticated internal mesh hands over everything.
- Authorizing on identifiers the client supplied. A tenant identifier in a request body is a claim, not a fact; derive it from the authenticated principal.
- One shared database account for every service. It makes least privilege impossible and blast radius maximal.
- Logging the payload. Tokens, card numbers and personal data end up in a log store with far weaker access control than the database they came from.
- Signing off a threat model and never reopening it. The model is a living artefact; a new integration invalidates it.
- Buying a scanner instead of making a decision. Tools find known bug classes; they cannot tell you that a service should not have had that permission.
Key takeaways
- Security is decided by architecture: assets, trust boundaries and blast radius determine what any later coding effort can achieve.
- A one-page data-flow diagram plus a STRIDE walk-through produces concrete, ownable controls faster than any document template.
- Least privilege, defence in depth, complete mediation, fail-secure, secure defaults and a small attack surface are the principles that keep repaying the effort.
- Put each control in the layer that cannot be bypassed: coarse rules at the edge, resource-level authorization in the domain, invariants in the database.
- Secrets belong in a manager or, better, are replaced by short-lived workload identity; anything committed to a repository must be rotated.
- Make the pipeline enforce the design — scanning, policy gates and authorization regression tests — and keep the threat model alive as the system changes.
Sources and further reading
Frequently asked questions
- When in a project should threat modelling happen?
- As soon as there is a sketch of the components and the data that moves between them, and again whenever that sketch changes materially — a new integration, a new data store, a new class of user. A first model on a whiteboard in an hour is worth more than a perfect document produced after the code is written, because at design time the fix is usually a different choice rather than a rewrite.
- Is defence in depth just duplicated work?
- No, because each layer fails differently. A gateway rule can be bypassed by an internal caller, a framework check can be skipped by a new code path, a database constraint cannot be skipped at all. Layers are chosen so that one control's blind spot is another's strength. What is wasteful is copying the same check into the same layer twice; what is valuable is the same invariant enforced by independent mechanisms.
- How do I convince a team to spend design time on security?
- Frame it as cost. A missing authorization check found on a diagram costs a conversation; found in production it costs an incident, a disclosure and a rushed patch. Bring one abuse case per user story into refinement, keep the model on the same board as the architecture, and record the decisions you made — including the risks you accepted deliberately — so nobody relitigates them later.
- Does zero trust replace network security?
- It replaces the assumption that being inside the network implies trust. Every request still has to be authenticated, authorized and, where possible, encrypted, whether it crosses the internet or a subnet. Network segmentation remains valuable as one more layer that limits how far an intruder can move, but it is no longer the boundary on which the whole design rests.