Authentication and authorization

Who you are versus what you may do, password hashing with bcrypt or Argon2, sessions versus tokens, MFA, and account enumeration.

11 min read🛡️ Application Security

Two words that get used interchangeably and mean different things, and almost every access-control bug lives in the gap between them.

  • Authentication — who are you? Proving identity. It happens once per request, at the edge.
  • Authorisation — may you do this? Checking permission. It happens per operation, and it needs to know what is being operated on.

A system can get the first perfectly right and still hand one customer another customer's invoice, because those are different questions asked at different moments.

The bug that follows from confusing them

java
@GetMapping("/orders/{id}")
public OrderView get(@PathVariable Long id) {
    return toView(orders.findById(id).orElseThrow());
}

The endpoint is behind a login. A request without a valid session is rejected before this method runs, so the code is authenticated. It is not authorised: nothing checks that this order belongs to the caller. Change 42 to 43 in the URL and you are reading somebody else's order.

This is the single most common serious flaw in real APIs, it has a name — broken object level authorisation, first on the OWASP API list — and it is invisible to every test that logs in and checks a 200.

The fix is to make the question part of the query:

java
Order order = orders.findByIdAndCustomerId(id, currentUser.getCustomerId())
                    .orElseThrow(OrderNotFoundException::new);

Note the shape: not fetch, then check, but fetch the thing this user is allowed to fetch. There is no window in which the object exists in a variable without the check having happened, and the failure is a 404 rather than a 403 — which is also the answer that does not confirm the order exists.

Where the check belongs

The rule that survives contact with a real codebase: authenticate at the edge, authorise where the data is.

Authentication is a filter's job — one place, one mechanism, every request. Authorisation is not, because a filter knows the URL and the method and nothing about which order, whose account, what state it is in. Pushing it into the controller is better; pushing it into the service layer, beside the query, is better still, because that is where every caller passes.

Roles, authorities and what they actually model

  • A role is a coarse label for a kind of user: ADMIN, SUPPORT, CUSTOMER.
  • An authority (or permission) is a specific action: order:refund, user:read.

Spring Security treats both as GrantedAuthority and only the naming convention differs — a role is an authority with a ROLE_ prefix. That is worth knowing because it explains why hasRole("ADMIN") and hasAuthority("ROLE_ADMIN") mean the same thing, which otherwise looks like a bug.

Which to use is a design question with a practical answer. Roles multiply badly. The moment somebody needs "support, but also allowed to issue refunds under ₹500", a role-only system grows SUPPORT_WITH_REFUNDS, and then a third variant, and then nobody can say what any of them can do. Permissions assigned to roles — the user has a role, the role grants a set of permissions, and the code checks permissions — keeps the check in the code stable while the policy moves.

There is a third model worth naming because you will meet it as a requirement rather than as a choice: attribute-based access control, where the decision depends on the data. "A manager may approve an expense, but not their own" is not a role, not a permission, and not expressible in an annotation. It is a rule about this user and this object, and it belongs in the service.

Principle of least privilege, applied to things that are not users

The idea is familiar for people. It is routinely forgotten everywhere else, and each of these is a real incident shape:

  • The database user your application connects as. It almost never needs DROP, and frequently does not need DELETE. An injection flaw in an application connected as the schema owner is a very different day from one connected as a user with SELECT and INSERT on eight tables.
  • The service account calling another service. Scope the token to what that integration does.
  • The deploy key, the CI token, the cloud role. Each one is a credential that will eventually be exfiltrated by something, and its blast radius is whatever you granted it.

Failing closed

When an authorisation check cannot be completed — the permissions service is down, a claim is missing from the token, the role is unrecognised — there are two possible defaults and only one of them is defensible.

java
// fails open: an unrecognised role is treated as harmless
if (user.getRole() == Role.ADMIN) return DENY_NOTHING;
return checkPermissions(user);
 
// fails closed: anything not explicitly permitted is refused
if (!permitted(user, action, resource)) throw new AccessDeniedException();

Default-deny is the property to design for, and the test that proves it is the one people do not write: a request with no permissions at all should be refused by every endpoint. A new endpoint added next year is then secure by omission rather than insecure by omission.

Under the hood: RBAC vs ABAC enforcement, and why the check has to run where the data already is

Role-based enforcement, mechanically, is a static check: it can be decided from the caller's identity alone, before anything about the specific request is loaded. Spring's @PreAuthorize("hasRole('ADMIN')") runs on the same kind of AOP proxy as @Validated (the request-validation lesson's "Under the hood" section) — the bean is wrapped at startup, and a method interceptor evaluates a SpEL expression against the GrantedAuthority set already sitting on the current Authentication, before the real method body ever runs. That is fast and cacheable precisely because it needs nothing the request itself carries beyond who is calling: the same check, for the same user, gives the same answer on every call to that method, regardless of arguments.

Attribute-based enforcement cannot be expressed that way, and the reason is structural, not a tooling gap: the decision — "a manager may approve an expense, but not their own" — depends on a value (whose expense is this?) that is only known once the specific object has been loaded, which an annotation on a method signature has no access to. There is no proxy that can intercept the call and answer "is this expense the caller's own" without first doing the fetch the method itself was going to do. That is exactly why ABAC-shaped rules live inline in the service, beside the query that already has both the subject (the caller) and the resource (the loaded row) in scope — not because it is a stylistic preference, but because that is the only point in the code where both pieces of information coexist.

This project's own admin surface is a concrete, real instance of "authorisation must be server-side," not just this lesson's or CLAUDE.md's rule stated abstractly. lib/server/admin-gate.ts runs inside every admin route, ahead of the handler's own logic, and answers with exactly two outcomes: null (a valid admin session — continue) or the panel's plain 404 — the same response a URL that names nothing at all would get. The check (isAdminRequest, in lib/server/admin-session.ts) is not a database lookup at all: the cookie itself is <expiry>.<uuid>.<HMAC-SHA256 of the first two fields>, keyed with a hash of ADMIN_PASSWORD, so verifying means recomputing that same HMAC server-side and comparing it in constant time — the same signature-recomputation mechanism this course's sessions-and-tokens lesson describes for a JWT, just with the whole application's one shared password as the key instead of per-user state. Nothing the client sends can shortcut it, because producing a matching HMAC requires the password; and when ADMIN_PASSWORD is not configured at all, no HMAC could ever have been issued with a matching key, so every admin route 404s the same way — fail-closed by construction, not by a default someone has to remember to set.

Try it yourself

Work out which model an endpoint needs, and why the check can't move earlier

A PATCH /expenses/{id}/approve endpoint has two rules: (1) only users with the MANAGER role may call it at all, and (2) a manager may not approve their own expense.

Before reading on: which rule is RBAC, which is ABAC, and at what point in the request-handling path does each one become answerable?

One rule is answerable at the edge; the other only after the row is loaded

Rule (1) is RBAC — it depends only on the caller's role, which is already known the instant the request is authenticated, so it can be (and should be) enforced as early as a method-level check, exactly like @PreAuthorize("hasRole('MANAGER')"). Rule (2) is ABAC — "not their own" depends on a fact about this specific expense (who submitted it) compared against a fact about the caller, and neither fact is available until the expense row has been fetched. Enforcing rule (2) any earlier than "after the load, before the mutation" is not just bad style, it is impossible: the information the rule needs does not exist yet at the point a route-level filter or a method annotation would run. This is also why moving rule (2) into the UI (disabling the "approve" button when expense.submittedBy === currentUser.id) is not a fix — the server-side load-then-check is the only point where both facts are guaranteed to be correct and current, and a client's copy of "who submitted this" can always be stale or simply skipped.

Misconceptions

  • "Checking a role claim inside a JWT is server-side authorisation." It is server-side authentication of a claim — proof the token says the caller has role MANAGER — which is a real and useful check, but it is not the object-level check this lesson opened with. A token proving "I am a manager" says nothing about whether this expense is one this manager may approve; that still needs a query, not a claim.
  • "Our API is only called by our own frontend, so the frontend's checks are the real authorisation." Anyone who can open developer tools, or simply run curl, can call the API directly with any body and any path parameter the client-side code would never have sent. "Only our frontend calls this" is not something the server can verify about an incoming request, so it is not a boundary at all — it is the same "the client is never trusted for it" rule this file already states, restated for the case where the client happens to be code you also wrote.

Sources

  • OWASP Access Control Cheat Sheet.
  • OWASP API Security Top 10 — API1:2023 Broken Object Level Authorization.
  • NIST Special Publication 800-162 — Guide to Attribute Based Access Control (ABAC) Definition and Considerations.
  • lib/server/admin-gate.ts and lib/server/admin-session.ts (this project's own fail-closed admin gate and its HMAC-signed session cookie).
Progress is saved on this device and to your account when signed in.