What you'll learn: By the end of this lesson you will be able to implement role-based, attribute-based and relationship-based authorization decisions on the server, say which kind of question each model answers, wire them into Spring method security with
@PreAuthorize, write one policy function that loads its own data and returns a reason, search a small relationship graph for the path that proves access, and order the checks so the system denies by default. A Spring Boot lab runs every decision through MockMvc.
An office building has three ways of deciding who gets in. The badge reader on the staff corridor checks only your role. The meeting-room booking system checks attributes: the room is free, the meeting is yours, it is inside working hours. The guest list at reception checks relationships: someone who works here invited you, or your team belongs to the department hosting the event. Each answers a different question, and a real building uses all three.
The front-end lesson RBAC and ABAC on the UI explains the models and why the browser only reflects a decision; its lab examples/frontend/labs/rbac-abac-model runs them in TypeScript. This lesson is the server-side partner: the server decides, with its own data, on every request. It builds on Authentication vs Authorization, Sessions vs Tokens, which says where the check sits; here we write it. Spring Security's architecture, OAuth and JWT validation are separate lessons (backend-spring-security-architecture, backend-oauth-2-and-openid-connect, backend-jwt-structure-and-pitfalls).
Verified with Spring Boot 4.1.2, Spring Security 7.1.2, Java 25 language level and the documentation pages listed at the end, on 2026-12-01.
The core idea
An authorization decision is a function from who is asking, what they want to do and to which resource, to allow or deny. Roles, attributes and relationships are three kinds of evidence that function can use, and the server must run it, with data the server owns, before every action.
Three labelled illustrations run through the lesson:
- Minimal example: two role-only endpoints,
hasRole('MANAGER')andhasRole('ADMIN'), in the lab. - Realistic example: ShopStream's seller console, where staff refund orders for their own shop, in "In practice".
- Failure example: an administrator role that is correct for the endpoint and wrong for the order, because the role says nothing about which shop the order belongs to.
Three kinds of evidence
Working definitions only; the front-end lesson has the longer comparison.
RBAC (role-based). NIST: each user is assigned one or more roles, and each role one or more privileges permitted to users in that role. The question: what kind of person is this.
ABAC (attribute-based). NIST: authorization determined by evaluating attributes of the subject, the object, the requested operation and sometimes the environment against policy, rules or relationships. The question: do the facts about this person and this record satisfy the rule. A refund limit on the person compared with the amount on the order is typical.
ReBAC (relationship-based). OWASP: access based on relationships between resources, such as a post's creator being allowed to edit it. The question: is there a path from this person to this object. Owners, members, teams and "shared with" lists live here.
OWASP says ABAC and ReBAC "should typically be preferred" for application development, and names RBAC's weak points: "role explosion" and poor fit for use cases with many distinct organizations or customers. Roles stay useful as a cheap, auditable gate ("this endpoint is for staff"); attributes and relationships answer the narrow questions.
| Model | Evidence | Answers | Weak at |
|---|---|---|---|
| RBAC | Roles held by the person | What kind of person? | Which record? Role explosion |
| ABAC | Attributes of person, resource, environment | Do the facts satisfy the rule? | Harder to explain who can do what |
| ReBAC | Relationships in a graph | Is there a path to this object? | Needs relationship data kept current |
Where the decision runs
The decision is made on the server, after authentication and before the action. OWASP: "Developers must never rely on client-side access control checks", permission "should be validated correctly on every request", and "an attacker only needs to find one way in".
Figure 1. One policy, three sources of evidence
How to read this: the client sends who it is and what it wants, and nothing the server trusts. The API calls the policy, and the policy looks up the person, the relationships and the order itself. Only the zone on the right can be believed.
Roles in Spring method security
Method security is switched on with @EnableMethodSecurity, after which any Spring-managed class or method can carry @PreAuthorize; Spring Boot's security starter does not activate it by default. hasRole('ADMIN') looks for the authority ROLE_ADMIN, because role rules use the prefix ROLE_ by default.
A role hierarchy lets one role include others: the Spring documentation says a user with the top role behaves as if they held all of them in filter- or method-based rules. For @PreAuthorize the hierarchy is given to the method-security expression handler, a static bean so Spring publishes it early. The lab follows the reference page; the API documentation marks setRoleHierarchy as deprecated since Spring Security 7.0 in favour of an AuthorizationManagerFactory, so check the current page for your version before copying:
@Bean
static RoleHierarchy roleHierarchy() {
return RoleHierarchyImpl.withDefaultRolePrefix()
.role("ADMIN").implies("MANAGER")
.role("MANAGER").implies("SUPPORT")
.build();
}
@Bean
static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
handler.setRoleHierarchy(roleHierarchy);
return handler;
}
and the two role-only endpoints, the minimal example:
@GetMapping("/reports/refunds")
@PreAuthorize("hasRole('MANAGER')")
Map<String, Object> refundReport() {
@DeleteMapping("/orders/{id}")
@PreAuthorize("hasRole('ADMIN')")
Map<String, Object> delete(@PathVariable String id) {
When the expression is false the method does not run: Spring throws AccessDeniedException, which ExceptionTranslationFilter turns into a 403. A caller with no credentials gets 401 from the filter chain first.
Figure 2. A role-only check in the request path
How to read this: authentication and authorization are different steps with different failure codes. The role check is cheap and happens before any data is loaded.
The weakness shows in the lab's output (the failure example). Ada is an ADMIN of shop t1; the delete rule only asks for the role, so it also accepts an order of shop t2.
Attributes: a policy function
When the rule depends on the record, the role is not enough. The lab puts those rules in one policy function: an expression can call a method on a bean with @beanName and pass method arguments by name, here #id. The refund endpoint combines role and policy:
@PostMapping("/orders/{id}/refund")
@PreAuthorize("hasRole('MANAGER') and @orderPolicy.permits(authentication, 'order.refund', #id)")
Map<String, Object> refund(@PathVariable String id) {
The policy never reads the request for the person's roles or shop. It takes the authenticated name, then loads the person and the order from the server's own data. The refund rule, in the order the lab applies it:
private Decision refund(Person person, Order order) {
if (order.owner().equals(person.name())) {
return deny("rule no-self-refund: nobody refunds an order they placed");
}
if (order.status().equals("frozen")) {
return deny("rule frozen-order: a frozen order cannot be changed");
}
if (!order.shop().equals(person.shop())) {
return deny("constraint same-shop not met: order is in shop " + order.shop() + ", person works in "
+ (person.shop().isEmpty() ? "no shop" : "shop " + person.shop()));
}
if (order.amount() > person.refundLimit()) {
return deny("constraint refund-limit not met: amount " + order.amount() + " is above the limit "
+ person.refundLimit());
}
return new Decision(true, "constraints hold: same-shop, refund-limit (" + order.amount() + " <= "
+ person.refundLimit() + ")");
}
Two habits to copy: deny rules come first, so no role or limit can override "never refund your own order", and every decision carries a reason and is written to an audit trail (DecisionLog); see Audit Logging.
Figure 3. The order the lab evaluates a refund
(hierarchy counts)"} B -->|"no"| D["403"] B -->|"yes"| C{"Own order or
frozen order?"} C -->|"yes"| D C -->|"no"| E{"Same shop and
within refund limit?"} E -->|"no"| D E -->|"yes"| OK["Allow (200)"]
How to read this: the role is the cheap wide filter, the deny rules are the absolute stops, and the constraints compare attributes of the person with attributes of the order. Reaching the bottom means nothing refused it.
Relationships: a small graph
Can this person see this order? The owner can, and so can anyone it was shared with, any member of the shop that holds it, and any member of a team that belongs to that shop. As attributes that is a growing pile of conditions; as a graph it is a few facts and two rules.
The lab stores facts as tuples, object#relation@subject, for example order:o-100#owner@user:ana. A subject can be a set, team:support-eu#member, meaning everyone in that team. Two rewrite rules say that order#viewer includes owner, shared and the member relation of the order's parent shop, and that shop#member includes shop#manager. This is the lab's own small model, not any product's syntax. Google's Zanzibar paper, whose abstract describes a global system for storing and evaluating access control lists with a uniform data model and configuration language, shows the idea at scale; the lab borrows only facts plus rules.
private static final Map<String, List<Rewrite>> REWRITES = Map.of(
"order#viewer", List.of(new Computed("owner"), new Computed("shared"), new FromParent("parent", "member")),
"shop#member", List.of(new Computed("manager")));
The search returns the steps that prove access, which makes the audit trail explain itself, and it keeps a visited set so a cycle between teams cannot loop forever.
Figure 4. A path from a person to an order
How to read this: solid arrows are stored facts, the dotted arrow is the conclusion. Revoking access means deleting one fact, not changing code.
Reading a record is one question and listing records is another. Spring's @PostFilter filters a returned collection in memory; the documentation warns that can be expensive and suggests filtering in the data layer. For a list, push the permission into the query.
Putting it together
A sound order inside one endpoint: authenticate (or 401); a coarse role where one exists; deny rules, then attribute constraints, then relationship paths, each loading its facts from the server's data; and deny by default. OWASP: "an application should be configured to deny access by default", deciding even when no rule matches. The lab denies an unknown person, order and action alike.
A missing order and a forbidden order both give 403 in the lab, so the answer does not reveal which ids exist. OWASP raises the distinction without prescribing a status, so choose deliberately; 404 for both is another consistent choice.
The other side of this topic
The front end gets its buttons from these answers and treats a 403 as an ordinary result. That half is in the front-end lesson linked above, whose lab shows the browser and server disagreeing about a stale button.
Build it: three models in Spring
This is the minimal example and its failure cases, run through a real filter chain. Not modelled: login, tokens, CSRF, a policy engine or relationship store, caching and list endpoints. The people, shops, orders and amounts are invented. There is no database: the data is in memory, and the tests use MockMvc.
Setup. From the repository (Docker is not needed):
cd examples/spring-labs
./gradlew :labs:rbac-abac-rebac:test
It runs 16 tests, one of which compares the report below with the golden file examples/spring-labs/golden/rbac-abac-rebac.txt. The code is in examples/spring-labs/labs/rbac-abac-rebac/. Tests hand the server an already authenticated person built from its own directory, with Spring Security's authentication(...) request post-processor and springSecurity() applied to MockMvc.
Roles. The hierarchy lets mia (MANAGER) and ada (ADMIN) read the report, sam (SUPPORT) is refused and an anonymous caller gets 401. Then the failure: nothing in the role limits Ada to her own shop.
Expected output, captured from a real run (Spring Boot 4.1.2, Spring Security 7.1.2, 2026-12-01):
== 1. Roles (RBAC): hasRole(...) with the hierarchy ADMIN includes MANAGER includes SUPPORT
GET /reports/refunds needs MANAGER: anonymous 401, ana (CUSTOMER) 403, sam (SUPPORT) 403, mia (MANAGER) 200, ada (ADMIN) 200
DELETE /orders/o-100 needs ADMIN: anonymous 401, ana (CUSTOMER) 403, sam (SUPPORT) 403, mia (MANAGER) 403, ada (ADMIN) 200
a role says what KIND of person; ada (ADMIN, shop t1) may delete an order of any shop, nothing in the role limits it
DELETE /orders/o-200 (a shop t2 order) as ada -> 200
Attributes. The same role, MANAGER, gets different answers because of the order: mia refunds within her shop and limit, and max, who manages shop t2, is stopped on a t1 order.
Expected output, captured from a real run (the same run):
POST refund o-100 as mia 200 (order: shop t1, owner ana, open, 4500)
constraints hold: same-shop, refund-limit (4500 <= 20000)
POST refund o-101 as mia 403 (order: shop t1, owner ben, shipped, 52000)
constraint refund-limit not met: amount 52000 is above the limit 20000
POST refund o-mia as mia 403 (order: shop t1, owner mia, shipped, 1500)
rule no-self-refund: nobody refunds an order they placed
POST refund o-102 as mia 403 (order: shop t1, owner ana, frozen, 900)
rule frozen-order: a frozen order cannot be changed
POST refund o-100 as max 403 (order: shop t1, owner ana, open, 4500)
constraint same-shop not met: order is in shop t1, person works in shop t2
Relationships. Each allowed read comes with the path in the graph. lee has no shop attribute and still reads o-200, through a team. Removing the shared tuple removes kim's access with no code change.
Expected output, captured from a real run (the same run):
GET /orders/o-200 as max -> 200
relationship found: order:o-200#viewer includes shop:t2#member through order:o-200#parent@shop:t2; shop:t2#member includes shop:t2#manager; shop:t2#manager@user:max
GET /orders/o-200 as lee -> 200
relationship found: order:o-200#viewer includes shop:t2#member through order:o-200#parent@shop:t2; shop:t2#member@team:support-eu#member; team:support-eu#member@user:lee
GET /orders/o-100 as lee -> 403
no relationship makes lee a viewer of order:o-100
GET /orders/o-999 as ada -> 403
no such order (deny by default)
revoke: remove the tuple order:o-100#shared@user:kim (a data change, no code change)
GET /orders/o-100 as kim -> 403 no relationship makes kim a viewer of order:o-100
restored: GET /orders/o-100 as kim -> 200
What the request claims is not read. The server looks the person up by the authenticated name, so a header or parameter that says ADMIN changes nothing.
Expected output, captured from a real run (the same run):
== 4. What the request claims is not read: the server looks the person up by the authenticated name
DELETE /orders/o-100 as ana with header X-Roles: ADMIN -> 403
DELETE /orders/o-100 as ana with parameter role=ADMIN -> 403
Break it. In OrderPolicy.refund, delete the if (order.status().equals("frozen")) { ... } block. Three tests then fail (theLimitAndTheDenyRulesApplyEvenToTheRightRoleInTheRightShop, aDenyRuleBeatsAnOtherwiseSufficientLimit and the golden-file comparison), because ada can refund the frozen order o-102: her limit covers it. The code was restored after this experiment and the tests pass again.
Stretch. Add a blocked relation that overrides every grant, test first; or add a decision-log entry for the role check that currently fails before the policy runs.
Trade-offs
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Roles only | Simple, auditable | Cannot say which record or shop | Rules depend on the record or tenant |
| Roles plus attribute policy | Per-record rules, few roles | A policy to write and test | Attributes are not available at decision time |
| Relationship graph | Sharing and revocation as data | Facts to keep current | Access is a plain function of a role |
| One policy bean from method security | One place to test and audit | An indirection to learn | The rule really is one role check |
In practice: seller staff refunding ShopStream orders
This is the realistic example, an educational scenario on the course's running example ShopStream, a grocery marketplace. It describes no real company, and every number is an illustrative assumption.
This is a realistic scenario, not a case history. It is a composite built from common production patterns.
The situation
Sellers on ShopStream have staff, and each staff member works for one shop. A new Refund action lets managers refund orders of their own shop up to a limit, customers can view their own orders and share one with a family member, and a support team covers two shops during part of the week. The first version checks one thing: the caller has the MANAGER role.
Starting architecture
Figure 5. Starting point: one role check, no record check
How to read this: the warning box is the gap. Any manager of any shop can refund any order whose id they can guess or find.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
A. Add shop and limit checks in the refund method |
Shop and amount enforced | Code in one handler | Other endpoints do not get the rule |
B. One policy bean, called from @PreAuthorize on every handler |
Shop, limit and deny rules in one tested place | A policy and a decision log to build | A route that forgets the annotation is open |
| C. Add a relationship graph for reading and sharing | Owners, sharing and teams without new roles | Facts to keep current | Stale relationships keep stale access |
The decision
| Field | Decision record |
|---|---|
| Context | Managers refund their own shop's orders within a limit, never their own orders; customers read and share their own orders; a team can cover a shop. |
| Decision | Role check for the coarse gate, a policy bean for refund attributes and deny rules, a relationship graph for reads. Deny by default; log every decision with its reason. |
| Consequences, good | A manager of one shop cannot touch another's orders; sharing and revocation are data changes; every refusal has a reason. |
| Consequences, bad | Relationship facts need an owner and a clean-up; list screens need permission-aware queries. |
| Revisit when | The number of rules or tenants outgrows one bean, which is the time to look at a policy engine. |
Rollout and verification
- Write table-driven tests first for each person and order, including every denial.
- Test that every route is protected: fail the build for any handler without an authorization annotation.
- Test revocation: remove a relationship and confirm the next request is refused.
- Watch the denial rate per action: a sharp change may be an attack or a broken rule.
The 2 a.m. failure
Support reports that a shop's staff suddenly cannot read any order. Logs show 403 with the reason "no relationship makes ... a viewer". A deploy changed how the team-to-shop fact is written, so the shop:t2#member@team:... tuple is no longer loaded.
First three checks: (1) read the decision log's reason for a denied request; (2) list the tuples for the shop and compare with the data store; (3) check the last deploy for changes to the loader. Mitigation: restore the loader or re-add the tuple. Do not widen a rule to "let everyone in" while the data is wrong. Follow-up: a test that loads the real seed data and asserts a known team member can read a known order.
Architect's notes
- Keep the policy in one place and call it from method security: one thing to test and audit.
- Load attributes yourself: take the authenticated name and fetch roles, shop and limit from your data, never from the request.
- Deny first, deny by default, and give every decision a reason you can log.
- Check the object, not just the endpoint, and test denials as carefully as allowances.
Common mistakes
- A role check and nothing else on an endpoint that takes a record id.
- Trusting a role, shop or limit sent by the client.
- Filtering a large list in memory instead of querying with the permission.
- Letting relationships go stale, so people keep access after leaving a team.
- Widening a rule during an incident because the data was wrong.
Key takeaways
- Authorization is a function from subject, action and resource to allow or deny, evaluated on the server on every request.
- RBAC answers what kind of person, ABAC whether the facts satisfy a rule, ReBAC whether a path exists.
- In Spring,
@EnableMethodSecurityplus@PreAuthorizeputs the rule beside the code; a role hierarchy bean must be given to the expression handler. - One policy bean, called from
@PreAuthorize, can load the person and the record itself and return a reason. - Deny rules first, then constraints, then relationships, then deny by default.
- A relationship graph turns sharing and revocation into data changes and can explain access as a path.
- Test the denials, the unknown cases and the revocation.
Practice exercises
Exercise 1 (20 min). For "read an order", "refund an order", "export all orders" and "change a shop's refund limit", say whether each is a role, attribute or relationship question, and why.
Exercise 2 (1 hour). In the lab, add a rule that a SUPPORT person may read but not refund, and write the tests first. Then add one blocked tuple that denies a named person and see where it must sit in the order.
Exercise 3 (half day). Design the permission-aware query for a "my orders" list for a person who is an owner, a shared viewer and a shop member. Say what you would index and what you would cache.
Related reading
- RBAC and ABAC on the UI: the front-end partner, with the lab
examples/frontend/labs/rbac-abac-model. - Authentication vs Authorization, Sessions vs Tokens: where the check sits and why it is repeated per object.
- Multi-Tenancy: the shop boundary as a tenant boundary.
- Audit Logging: what to keep from each decision.
- SSRF and the OWASP API Security Top 10: broken object-level authorization as a top API risk.
- Security for Distributed Systems: the wider threat model.
Official documentation
- Spring Security reference, Method Security and Authorization Architecture (hierarchical roles).
- Spring Security reference, Testing with MockMvc: authentication.
- OWASP, Authorization Cheat Sheet.
- NIST, Role Based Access Control and SP 800-162, Guide to ABAC Definition and Considerations.
- Google Research, Zanzibar: Google's Consistent, Global Authorization System (abstract only read).