Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
Noah is logged in, so the URL rule lets him read Olivia's ticket 12. A @PreAuthorize rule on TicketService.get, with a small TicketAccess bean, gives Noah 403 and Olivia and the agent 200. Remove one annotation and the hole silently opens again.
What you will learn
- Explain why a URL rule cannot stop one customer reading another's ticket
- Turn on @EnableMethodSecurity and guard a service method with @PreAuthorize
- Call an ownership-check bean from a SpEL rule with #id and authentication.name
- Tell roles from authorities and the ROLE_ prefix
Before you start
- Users in the Database with Spring Security
- The Spring Security Filter Chain and Your Own Rules
Relay's tickets are safe from strangers. They're not yet safe from each other. Ticket 12, "Change the account email address", belongs to Olivia Bennett:
id | subject | name | email
----+----------------------------------+----------------+----------------------------
12 | Change the account email address | Olivia Bennett | olivia.bennett@example.com
Noah Carter, another customer, logs in and asks for it:
curl -i -s localhost:8080/api/tickets/12 -H "Authorization: Bearer $NOAH"
HTTP/1.1 200
Content-Type: application/json
{"id":12,"subject":"Change the account email address",
"customer":"Olivia Bennett","assignee":"Liam Foster", ...}
Why does that work? The URL rule, anyRequest().authenticated(), asks one question: are you logged in? Noah is. Nothing asks whose ticket it is. A URL rule can't know that, because the answer depends on the data. So the rule has to move to where the data is: the service method.
Step 1: switch method security on
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
// the URL rules stay exactly as they were
}
Now Spring reads @PreAuthorize on your methods. The URL rule stays: it keeps strangers out.
Step 2: the ownership question as a bean
One derived query in TicketRepository:
boolean existsByIdAndCustomerEmail(Long id, String email);
And a small bean that asks it:
/** Does this ticket belong to the person asking? */
@Component
public class TicketAccess {
private final TicketRepository tickets;
public TicketAccess(TicketRepository tickets) {
this.tickets = tickets;
}
public boolean isOwner(Long ticketId, String email) {
return tickets.existsByIdAndCustomerEmail(ticketId, email);
}
}
Step 3: the rule on the method
@PreAuthorize("hasAnyRole('AGENT', 'ADMIN') "
+ "or @ticketAccess.isOwner(#id, authentication.name)")
public TicketDetail get(Long id) {
Read it left to right. Staff (agents and admins) may read any ticket. Otherwise, the caller must own it. In the expression, #id is the method's own parameter, authentication.name is the e-mail from the token, and @ticketAccess is the bean (its name is the class name with a lower-case first letter). The method body runs only when the rule says yes.
Three people, one URL
Noah -> HTTP 403 (WWW-Authenticate: Bearer error="insufficient_scope" ...)
Olivia -> HTTP 200
Liam -> HTTP 200
Noah isn't staff and doesn't own ticket 12, so 403. Olivia owns it, so 200. Liam is an agent: the first half of the rule is already true, so ticketAccess is never even asked.
Roles and authorities
A small /api/me endpoint shows what Spring holds for each caller:
{"username":"liam.foster@relay.example","roles":["AGENT"],"authorities":["ROLE_AGENT","FACTOR_BEARER"]}
{"username":"noah.carter@example.com","roles":["CUSTOMER"],"authorities":["ROLE_CUSTOMER","FACTOR_BEARER"]}
Liam's token carries a roles claim with AGENT. Relay's config puts ROLE_ in front, so Spring holds the authority ROLE_AGENT. hasRole('AGENT') looks for exactly ROLE_AGENT, the same as hasAuthority('ROLE_AGENT'). So a role is just an authority with ROLE_ in front. Noah holds ROLE_CUSTOMER, the staff check is false for him, and the rule falls through to the ownership check.
Break it: delete the switch
Remove @EnableMethodSecurity, leave everything else, restart, and call ticket 12 as Noah: HTTP 200 again. No error, no warning in the log. The @PreAuthorize is still there on the method, but nobody reads it. This is the dangerous kind of bug: it looks secure in a code review. A test that calls ticket 12 as Noah and expects 403 would catch it (see Testing Secured Endpoints).
Common mistakes
- Only URL rules. They can check "logged in" and "has role", never "owns this row".
- Forgetting
@EnableMethodSecurity. Every@PreAuthorizesilently does nothing. - Putting the check in the controller only. Another controller, or a batch job, calls the service and skips it. Guard the service.
- Calling the guarded method from inside the same class. Like
@Transactional, the guard lives on Spring's proxy, so a self-call skips it.
Recap
| Piece | Job |
|---|---|
| URL rule in the chain | keeps strangers out (401) |
@EnableMethodSecurity | the switch that makes Spring read method rules |
@PreAuthorize(...) | decides per call, before the method runs (403) |
@ticketAccess.isOwner(#id, authentication.name) | asks the data whose ticket it is |
hasRole('AGENT') | same as hasAuthority('ROLE_AGENT') |
Try it yourself
Add a rule to the comment-adding method so a customer can comment only on their own ticket, while agents can comment on any. Which parameter name do you put after #?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
A RegisterForm record with three annotations checks the name, email and password at the door. Bad data goes back to the form with a message under each field; good data becomes an Account row. And the password is still stored as plain text, which the next step fixes.
Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
A guard at the gate and a hash in the table. A SecurityFilterChain lists the open pages and sends everything else to /login, a BCrypt PasswordEncoder bean hashes every password, and a UserDetailsService answers 'who is this email?' from the ACCOUNT table.
Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
Until now every login got .roles("USER") typed into the code. A Role enum on Account, one changed line in the UserDetailsService and one hasRole rule let Chaand open /admin while Emma gets a 403 and a visitor is sent to log in.
Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
One header file, three menus: a visitor sees Register and Login, Emma sees her email and Logout, Chaand also gets Admin. Then each post knows its author through @ManyToOne, and the Edit button shows only for the author or an admin.
