Authorization, SSO and OAuth2: from RBAC to OpenID Connect
Why checking roles isn't enough and changing an id in the URL leaks other users' data: roles + permissions, ownership checks, ABAC/ReBAC, parent-domain-cookie SSO versus a central IdP + OpenID Connect, OAuth2 versus OIDC, OAuth 2.1 and Spring Security 7; how to review AI-written authorization code.
On this page
1. The problem
A booking API checks hasAuthority('bookings:read') and returns findById(id). A customer changes /bookings/1042 to /bookings/1043 and scripts through the range: 38,000 bookings leak in one night.
2. Key idea
"What may you do" and "on which object" are different questions; a permission only answers the first. Broken Access Control is number one in the OWASP Top 10.
| Question | Answered by | Missing it means |
|---|---|---|
| Who are you | authentication: session, JWT, IdP | anyone can call the API |
| What kind of action | a permission (bookings:read) |
regular users call admin APIs |
| On which object | owner_id, tenant_id in the query |
IDOR: change the id, read someone else's data |
2.1 Which model?
Pick the simplest model that's enough. For every id from a client, ask "whose is it?" and return 404 so you don't reveal that the object exists.
| Model | Use when | Don't use when |
|---|---|---|
| Pure RBAC (check roles) | internal systems, 2–3 roles, rarely changing | overlapping roles, permission changes need a deploy |
| Roles + permissions | the default for most backends | rules depend on attributes or relationships |
| Parent-domain cookie for SSO | two internal apps on one domain | apps on other domains, external users |
| IdP + OpenID Connect | three or more apps, MFA, social login, partners | a single app |
2.2 How do OAuth2 and OIDC differ?
OAuth 2.0 is delegation: the access token tells the API what the client may do (scope). OpenID Connect is authentication: the ID token tells the app who the user is. For login, check the ID token; never use an access token as proof of login. Clients with users use authorization code + PKCE; implicit and password grants are gone.
3. In Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(a -> a
.requestMatchers(HttpMethod.POST, "/flights").hasAuthority("SCOPE_flights:create")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) // scope -> SCOPE_*
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
@GetMapping("/bookings/{id}")
@PreAuthorize("hasAuthority('SCOPE_bookings:read')") // needs @EnableMethodSecurity
BookingDto get(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) {
return bookings.findByIdAndOwnerId(id, Long.parseLong(jwt.getSubject())) // ownership in the query
.map(BookingDto::from)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}hasRole('ADMIN') looks for the authority ROLE_ADMIN, not ADMIN. Spring Security 7 (Boot 4) only has the lambda-style DSL.
Permissions in tokens, multi-tenancy and cookie-based SSO
| Where permissions live | Gain | Cost |
|---|---|---|
In the token (scope claim) |
no DB call | permissions stale until expiry; headers over 8 KB hit proxy limits |
| Looked up per request (DB/cache) | near-instant revocation | one more lookup |
| Both | 5–15 minute tokens, sensitive permissions re-checked | more complexity |
- Roles + permissions: code says
hasAuthority('flights:create')and never changes; giving SUPPORT the cancel permission is oneINSERT INTO permission_binding. - Multi-tenancy:
role_bindinghas atenant_id, the token carries the active tenant, every query filters by tenant (Hibernate@TenantId). PostgreSQL Row-Level Security adds another layer. - SSO via a
Domain=domain.comcookie: every subdomain (a blog, an agency landing page, a CNAME pointing at a cancelled service) can read and overwrite the token; one taken-over subdomain is enough to hijack sessions. Adding an app on another domain means starting over. - An IdP (Keycloak, Auth0, Entra ID) holds passwords, MFA and the global session; each app has its own host-only
__Host-cookie. Logout: back-channel logout (the IdP calls each app server-to-server) is the most reliable. - ABAC (OPA, Cedar) for attribute rules ("the Hanoi branch only edits flights departing HAN"); ReBAC (OpenFGA, SpiceDB) for sharing and hierarchy ("sharing a folder lets you see its files").
- ID tokens are always JWTs; check
iss,aud(your client id),exp,nonce. PKCE: the client sendsSHA256(code_verifier)and later the verifier, so an intercepted code is useless. OAuth 2.1 is still a draft that bundles RFC 9700's best practices.
4. Working with AI
Delegate to AI: resource server configuration, authority converters, authorization tests covering all four cases.
Check yourself:
- Every endpoint taking an id from the client has an ownership or tenant condition in the query, returning 404.
-
hasRoleandhasAuthoritymatch the converter's prefix convention. - Access tokens are short-lived; the API checks
issandaud, not just the signature.
5. Exercises
Exercise 1: Review "only ADMIN or the booking owner can cancel"
The project's converter maps the roles claim to unprefixed authorities (ADMIN). Find the bugs, name tests, fix them.
@DeleteMapping("/bookings/{id}")
@PreAuthorize("hasRole('ADMIN') or hasAuthority('SCOPE_bookings:cancel')")
void cancel(@PathVariable long id) {
Booking b = bookings.findById(id).orElseThrow(NotFound::new);
b.cancel();
bookings.save(b);
}Solution to Exercise 1
- IDOR: any customer with
bookings:cancelcan cancel anyone's booking, sincefindById(id)doesn't filter by owner. Fix:findByIdAndOwnerId(id, userId(jwt)), returning 404. - Prefix:
hasRole('ADMIN')looks forROLE_ADMINbut the converter producesADMIN, so real admins always get 403. Fix:hasAuthority('ADMIN')or configure the converter to addROLE_. - An admin cancelling someone else's booking is a separate branch: check admin rights first, write an audit log.
- Tests: A cancels B's booking → 404; an admin cancels any booking → 204; a customer without the scope → 403; no token → 401.
Exercise 2: Read a revocation incident
An operator leaves at 9:00 and an admin removes their role in the DB at 9:05. The audit log shows the account successfully calling POST /flights at 11:40. Access tokens live 24 hours, carry a scope claim, and the API only checks the signature and exp. Diagnose, act within 15 minutes, fix the root cause.
Solution to Exercise 2
- Cause: a token issued before 9:05 still carries
flights:createand is valid until tomorrow; the API never re-checks permissions. - 15 minutes: add the
subto a blocklist the resource server checks (without one, rotate the signing key and accept everyone logging in again); revoke refresh tokens and the IdP session; review the audit log from 9:00. - Root fix: 5–15 minute access tokens; re-check current permissions when refreshing; sensitive operations check permissions at the source of truth; the offboarding process calls the IdP's revocation API.
Summary
- Three questions: who, what, on which object; missing the third is IDOR.
- Code checks permissions; roles are data; ownership lives in the query, returning 404.
- Permissions in tokens go stale until expiry: short tokens, re-check sensitive actions.
- Standard SSO is an IdP + OIDC, not a parent-domain cookie.
- OAuth2 delegates, OIDC authenticates; authorization code + PKCE for every client.
Further reading: Rotating refresh tokens and permissions in Spring.
Practice interview questions on this topic
- How does OAuth 2.0 differ from OpenID Connect, and why does the authorization code flow need PKCE?
- How do you design SSO properly: parent-domain cookies, logout, and linking accounts by email?
- What is RBAC, what are its limits, and why check permissions rather than roles?
- How do authentication and authorization differ, and what about 401 vs 403?
- A user changes /orders/123 to /orders/124 and sees someone else's order: what's the bug and the fix?
- An AI wrote a `transactions(customerId, days)` tool for an agent. How do you review it, and how do you authorise an agent's tools?
Comments
Community rules