Authorization with roles, permissions, ownership & method security
Authentication vs authorization, URL rules vs @PreAuthorize, RBAC vs permission-based access, custom annotations, object-level (ownership) checks and the IDOR bugs they prevent.
The concept
- Authentication answers who are you? (JWT, password, OAuth).
- Authorization answers what may you do?, at three levels:
| Level | Question | Tool |
|---|---|---|
| URL / route | Can this role call /admin/** at all? |
SecurityFilterChain requestMatchers(...) |
| Method / action | Can this user call approveBooking? |
@PreAuthorize, custom annotations |
| Object (row) | Can this user approve this booking or see this order? | Ownership checks, specs, tenant filters |
RBAC vs permissions
- Role-based (RBAC):
hasRole('MANAGER'). Simple, but roles get overloaded (“MANAGER_BUT_CAN_EXPORT”). - Permission-based: roles are bundles of fine-grained permissions (
GET_ACCOUNTS,APPROVE_REPORT), and code checks permissions, not roles. New roles need no code change.
@EnableMethodSecurity
// ...
@PreAuthorize("hasRole('STUDENT')") // checks ROLE_STUDENT
public BookingDto create(...) {}
@PreAuthorize("hasAuthority('APPROVE_REPORT')")
public void approve(UUID id) {}
@PreAuthorize("@bookingSecurity.isOwner(#id, authentication)") // SpEL to a bean
public BookingDto get(UUID id) {}
In your projects
SecurityConfig · OrderService.getOrderByIdURL rules: .requestMatchers("/admin/**").hasRole(Role.ADMIN.name()). Object-level check: if (!order.isPlacedBy(user)) throw new AccessDeniedException(...).
The analysis found two gaps, both fixed in Store PR #1:
- Product POST/PUT/DELETE had no admin check. Now
requestMatchers("/products/**").hasRole(ADMIN), with GET left public. - User GET/PUT/DELETE had no ownership check, so any logged-in user could edit or delete any other user. This is a classic IDOR (Insecure Direct Object Reference). Now an
isSelfOrAdmin(id, auth)check compares the path id with the JWT principal.
/carts/** stays permitAll on purpose. Carts are anonymous guest carts identified by a random UUID, which works like an unguessable key, and checkout still requires login. That’s a deliberate design trade-off, not a bug.
UserRole (STUDENT, MANAGER, ADMIN) · BookingControllerClean RBAC with three roles and @PreAuthorize("hasRole('STUDENT')") per endpoint, tested with @WebMvcTest plus MethodSecurityTestConfig (401/403 cases).
shared/enums/PermissionName.java · PermissionDataInitializer · 123 x @PreAuthorizePermission-based. User ↔ Role ↔ Permission are many-to-many, the permissions are an enum seeded at startup, and endpoints use @PreAuthorize("hasAuthority('GET_ACCOUNTS')"). Object-level access is enforced through ReportSubmissionSpecs.isAccessibleBy(approvableUnitIds, callerUnitId).
@RequiresPermission (148) · user/enforcement · AdminRole · StaffMfaSetupFilterCustom @RequiresPermission(Permission.AUDIT_LOG_VIEW) with an enforcement aspect, plus @RequireActiveMode. Admin URLs require hasAnyRole("ADMIN","SYSTEM_ADMIN"). Staff without MFA are restricted to the MFA setup page by a filter. RestrictedAccessRecorder logs 403s for security review.
RoleCatalogue · @RequirePermission · @MembersOnly · PermissionAspect · ApiTokenFilterPermissions are per company. A user can be an Owner in company A and a Viewer in company B. TenantResolutionFilter loads that membership’s permissions into TenantContext, and PermissionAspect checks @RequirePermission. Company API tokens (machine users) and platform staff are separate actor types. The single super-administrator rule is enforced in migration 017.
Alternatives
| Model | When |
|---|---|
| RBAC | Few, stable roles (Hostel) |
| Permission-based RBAC | Business apps with configurable roles |
| ABAC (attribute-based) | Rules like “managers can approve bookings in their own hostel under GHS 5000” |
| ReBAC (relationship-based, Google Zanzibar, OpenFGA, SpiceDB) | Sharing and hierarchies (“editor of folder implies editor of its docs”) |
| Policy engines (OPA/Rego, Cedar) | Centralised policy across many services |
| Postgres RLS | Enforced in the DB itself |
Related concepts you must know
- Deny by default. End your filter chain with
.anyRequest().authenticated(), and neverpermitAllby accident. - IDOR / BOLA is #1 in the OWASP API Top 10 (Broken Object-Level Authorization). Every
/{id}endpoint needs an ownership or tenant check. - Hiding vs authorizing. Hiding a button in React isn’t security; the API must check.
- Return 404 vs 403. Answering 404 for “exists but not yours” avoids leaking that the resource exists.
ROLE_prefix.hasRole('X')checksROLE_X, whilehasAuthority('X')checks exactlyX.