BBackend CourseLeroy Labs
0/0
Search the course

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.

● intermediateSpring-Boot-StoreHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

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

Spring-Boot-StoreSecurityConfig · OrderService.getOrderById

URL 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.

Hostel-Web-AppUserRole (STUDENT, MANAGER, ADMIN) · BookingController

Clean RBAC with three roles and @PreAuthorize("hasRole('STUDENT')") per endpoint, tested with @WebMvcTest plus MethodSecurityTestConfig (401/403 cases).

Report-Manager-2shared/enums/PermissionName.java · PermissionDataInitializer · 123 x @PreAuthorize

Permission-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).

IR3D (Kontentt)@RequiresPermission (148) · user/enforcement · AdminRole · StaffMfaSetupFilter

Custom @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.

SperoTek (in dev)RoleCatalogue · @RequirePermission · @MembersOnly · PermissionAspect · ApiTokenFilter

Permissions 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
  • Deny by default. End your filter chain with .anyRequest().authenticated(), and never permitAll by 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') checks ROLE_X, while hasAuthority('X') checks exactly X.

Check yourself

1. GET /orders/{id} returns any user’s order if you know the id. This is…
2. hasRole("ADMIN") checks for authority…
3. "Managers may approve only bookings in their own hostel" is best expressed with…