Picture a system with no security:
- “Show me my orders.” “Here are everyone’s orders.”
- “Make me an admin.” “Done.”
- “Delete all the data.” “Done.”
Nobody builds that on purpose. But every real breach starts with one small gap: a missing check, a leaked password, an endpoint someone forgot to protect. In 2017, Equifax lost the personal data of about 147 million people because of a web server that hadn’t been patched.
“Security isn’t a feature you add at the end. It’s part of the design from day one.”
This article covers the security ideas every system designer needs. It’s part of the Observability, security & operations thread.
What are we protecting? The CIA triad
Security has three goals, usually called the CIA triad:
| Goal | Meaning | Example |
|---|---|---|
| Confidentiality | Only the right people can see data | User A can’t see User B’s orders |
| Integrity | Data can’t be changed by the wrong people, or by accident | A customer can’t change the price of an order after paying |
| Availability | The system stays up for real users | A flood of fake traffic doesn’t take the site down |
Most of what follows protects one of these three.
Authentication vs authorization
These two words sound alike and are often mixed up, but they are separate checks:
- Authentication (authn): who are you? Proving identity: a password, a one-time code, a fingerprint, “Sign in with Google”.
- Authorization (authz): what are you allowed to do? Checking permissions: can this user see this order, or delete this product?
You always need both. A common bug is an admin endpoint that checks you’re logged in but not that you’re an admin, so any user can call it. In Spring Security, the check is one line:
// Java · Spring Security: must be logged in AND an admin
@GetMapping("/api/admin/users")
@PreAuthorize("hasRole('ADMIN')")
public List<User> allUsers() {
return userService.findAll();
}
Sessions vs JWT: how a server remembers you
After you log in, the server needs to recognise you on every later request. There are two common ways.
Sessions: the server creates a session, stores it (in memory, Redis or a database) and gives the browser a random session ID in a cookie. On each request, the server looks up the ID.
Tokens (JWT): the server gives you a signed token, a JSON Web Token, that contains facts about you, like your user ID, role and an expiry time. On each request you send it back (usually in an Authorization: Bearer … header), and any server can check the signature without looking anything up.
| Sessions | JWT | |
|---|---|---|
| Where the user data lives | On the server | Inside the token |
| Each request | Look up the session | Check the signature |
| Log someone out now | Easy: delete the session | Hard: the token is valid until it expires |
| Works across many services | Needs a shared session store | Yes, any service with the key can check it |
| Good fit | Classic web apps | APIs, mobile apps, microservices |
The big JWT catch: you can’t easily take one back. If a token lasts 24 hours and a phone is stolen, the thief has 24 hours. The usual fix:
- Make access tokens short-lived, around 15 minutes.
- Give a separate refresh token, stored safely and checked against the database, to get new access tokens.
- To log someone out everywhere, cancel their refresh token. Within 15 minutes, their access tokens run out too.
And two JWT rules: never put secrets in the payload (it’s only encoded, not encrypted, so anyone can read it), and always check the signature and expiry with a proper library.
OAuth 2.0 and OpenID Connect: “Sign in with Google”
Suppose your app wants to read a user’s Google Calendar. The terrible way is to ask for their Google password. Now you can read their email, change their password, everything.
OAuth 2.0 solves this with delegated access. Your app sends the user to Google. Google asks the user, “Allow this app to read your calendar?” If they say yes, Google gives your app an access token that can only read the calendar, expires soon, and can be revoked by the user at any time. Your app never sees the password.
OpenID Connect (OIDC) is a thin layer on top of OAuth 2.0 that adds who the user is. That’s what powers “Sign in with Google” or “Sign in with Microsoft”: you get a signed ID token saying who logged in, so you don’t have to store passwords at all.
In short: OAuth is about access (what an app can do on your behalf); OIDC is about identity (who you are).
Authorization: who can do what
Once you know who someone is, there are three common ways to decide what they can do:
- Role-based (RBAC): permissions come from roles.
USERsees their own orders;SUPPORTcan view any order;ADMINcan do everything. Simple and good for most apps. - Ownership checks: the user can only touch their own records. This check must be on every endpoint that takes an ID.
- Attribute-based (ABAC): rules use attributes of the user, the data and the situation. “Support staff can see orders in their own region, during working hours.”
Always follow least privilege: give every user, service and database account the smallest set of permissions it needs, and deny by default.
Four attacks every web app must stop
These come up again and again in real breaches and on the OWASP Top 10 list:
| Attack | What happens | The fix |
|---|---|---|
| SQL injection | User input is glued into a SQL string. An input like ' OR '1'='1 changes the query and returns or deletes other people’s data |
Always use parameterised queries (prepared statements or an ORM). Never build SQL by joining strings |
| Cross-site scripting (XSS) | An attacker saves a comment containing <script>. Every visitor’s browser runs it, and it can steal their session |
Escape user content when showing it (modern frameworks do this by default), and add a Content Security Policy |
| IDOR (insecure direct object reference) | A user changes /orders/123 to /orders/124 in the URL and sees someone else’s order |
Check ownership on every request: “does this order belong to this user?” |
| CSRF (cross-site request forgery) | You’re logged into your bank. A bad site makes your browser send a “transfer money” request, and your cookie goes along with it | CSRF tokens for cookie-based forms, and SameSite cookies |
Here’s the IDOR fix in code. It’s the check most often forgotten:
@GetMapping("/api/orders/{id}")
public Order getOrder(@PathVariable long id, @AuthenticationPrincipal AppUser me) {
Order order = orders.findById(id).orElseThrow(NotFoundException::new);
if (!order.ownerId().equals(me.id()) && !me.isAdmin()) {
throw new NotFoundException(); // don't even reveal that it exists
}
return order;
}
The single rule behind all four: never trust input from the user. Check it, use it safely, and escape it when you show it.
DDoS: protecting availability
A DDoS (distributed denial of service) attack floods you with traffic from thousands of machines, so real users can’t get in. You can’t stop it in one place, so you stop it in layers:
- At the edge: a CDN or DDoS service (Cloudflare, AWS Shield, Google Cloud Armor) soaks up huge floods before they reach you.
- A web application firewall (WAF): blocks known bad patterns and suspicious IPs.
- Rate limiting: caps requests per IP, user or API key, so no one client can use everything.
- Inside your app: serve cached pages, turn off expensive features, and use a CAPTCHA for suspicious traffic.
Secrets: keep keys out of your code
Passwords, API keys and signing keys must never be written into source code. Once committed, they live in your Git history forever and are visible to everyone with access.
- Minimum: read secrets from environment variables, never from committed files.
- Better: use a secrets manager (AWS Secrets Manager, Google Secret Manager, HashiCorp Vault). Secrets are encrypted, access is logged, and you can rotate them without a code change.
- Encrypt data in transit (HTTPS/TLS everywhere, including between your own services) and at rest (database and backup encryption).
What breaks, and how to fix it
| What breaks | What you see | The fix |
|---|---|---|
| The login service goes down | No one can log in, and if every request checks with it, nothing works at all | Services verify JWT signatures locally using cached public keys, so existing users keep working |
| The rate limiter’s Redis goes down | No more limits, just when you might be under attack | Fall back to a simple in-memory limit per server instead of turning limits off |
| A secret leaks (e.g. pushed to GitHub) | Attackers use the key within minutes | Rotate it at once; use a secrets manager so rotation is quick; scan commits for secrets |
| One missing check | One endpoint without an ownership check exposes all records | Deny by default; test that every endpoint rejects other users’ IDs |
Puzzle 1: the token that wouldn’t die
A JWT is valid until it expires, no matter what changes on the server. Some options:
- Short access tokens + refresh tokens (the best default). Access tokens last ~15 minutes. Changing the password cancels the user’s refresh tokens, so the thief is out within 15 minutes.
- A token version. Store a
tokenVersionnumber on the user and put it in each token. Changing the password increases it, and tokens with an old version are rejected. This is instant, but every request now needs a quick lookup, which gives up some of JWT’s “no lookup” benefit. - A block list of cancelled token IDs in Redis, checked on each request. Also instant, with the same lookup cost.
Most systems use the first, and add the second or third for sensitive actions.
Puzzle 2: CSRF protection broke the mobile app
CSRF attacks work because browsers send cookies automatically to a site, even when a different site triggers the request. CSRF tokens prove the request came from your own page.
The mobile app doesn’t use cookies. It sends a JWT in the Authorization header, which a browser never adds by itself, so CSRF isn’t possible there. But it also never had a CSRF token to send, so every request failed.
The fix: use CSRF protection where auth uses cookies (the website), and skip it for routes that only accept bearer tokens in a header (the mobile API). In Spring Security, that means two security filter chains with different rules. And if your website stores tokens in cookies too, keep CSRF on for it.
Key takeaways
- Security protects confidentiality, integrity and availability, and it’s designed in, not added later.
- Authentication asks who you are; authorization asks what you may do. Check both, on every request.
- Sessions are easy to revoke; JWTs scale well across services. Use short-lived JWTs with refresh tokens.
- OAuth 2.0 gives limited, revocable access without passwords; OpenID Connect adds sign-in.
- Stop the big four: SQL injection, XSS, IDOR and CSRF. Never trust user input.
- Defend in layers: edge protection and rate limiting for DDoS, a secrets manager for keys, encryption everywhere, and least privilege for everything.
That completes the Observability, security & operations thread: observability, deployment strategies and security. Next in the series, we’ll put everything together into a framework for answering any system design interview.
Comments