@PreAuthorize Annotation in Spring Security
@PreAuthorize is the most flexible authorization annotation in Spring Security. It holds a Spring Expression Language (SpEL) expression that must be true before the annotated method is allowed to run. The expression can look at the user's roles, the method's arguments and even call your own Spring beans.
This tutorial goes deeper than the overview in Spring Security annotations: it covers the expression vocabulary, moving complex rules into a policy bean, and creating your own annotations, including templated ones, so rules stay short and consistent. The example is a hospital shift-swap service where nurses request swaps and charge nurses approve them.
1. What Is @PreAuthorize?
@PreAuthorize is a method security annotation from org.springframework.security.access.prepost. When a method carrying it is called through a Spring proxy, the AuthorizationManagerBeforeMethodInterceptor evaluates the expression. If the result is false, the method body never runs and an AuthorizationDeniedException is thrown; in a web request this becomes 403 Forbidden.
It requires @EnableMethodSecurity on a configuration class, and it can be placed on a method, on a class (applying to all its methods) or on an interface. How the proxy works is covered in method-level security.
2. Why Use @PreAuthorize?
- Rules that depend on data. "A nurse may request a swap only for their own shift" compares an argument with the current user, which URL rules cannot do.
- Protection for every caller. The check runs whether the method is called from a controller, a message listener or a scheduled job.
- Fail before side effects. Unlike
@PostAuthorize, nothing is executed or written when the check fails.
3. How the Expression Is Evaluated
3.1 The Expression Vocabulary
| Expression | True when |
|---|---|
hasRole('NURSE'), hasAnyRole('A', 'B') | The user has ROLE_NURSE (or any listed role) |
hasAuthority('swap:approve') | The user has that exact authority |
isAuthenticated(), isAnonymous() | The user is logged in, or is anonymous |
authentication.name, principal | Access to the current user, for comparisons |
#request.requestedBy() | Uses a method argument by its parameter name |
@wardPolicy.isChargeNurse(authentication.name, #ward) | Calls a method on the Spring bean named wardPolicy |
and, or, not, ==, != | Combine and compare |
Argument names come from the compiled class, which requires the -parameters compiler flag. Spring Boot's Maven and Gradle plugins set it for you. If you compile another way, name the argument explicitly with @P("ward") from org.springframework.security.core.parameters.
4. A Complete Example: Shift Swaps in a Hospital
Nurses request shift swaps for their own shifts. Each ward has one charge nurse, and only that person may approve swaps on their ward. The HR team reads an overtime report. The API is called by the hospital's rostering app with HTTP Basic and no cookies, so CSRF protection is disabled. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.
package com.javabytechie.rostering;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class ShiftSwapService {
public record SwapRequest(String shiftId, String ward, String requestedBy) {}
// 1. Arguments: nurses may only request swaps for themselves
@PreAuthorize("hasRole('NURSE') and #request.requestedBy() == authentication.name")
public String requestSwap(SwapRequest request) {
return "Swap requested for " + request.shiftId() + " by " + request.requestedBy();
}
// 2. Custom meta-annotation that calls a policy bean
@IsChargeNurseOfWard
public String approve(String ward, String swapId) {
return swapId + " approved on " + ward;
}
// 3. Templated meta-annotation
@RequireRole("HR")
public List<String> overtimeReport() {
return List.of("meena: 6 h", "joseph: 2 h");
}
}
package com.javabytechie.rostering;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.access.prepost.PreAuthorize;
// One readable name for a rule used in several places
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('CHARGE_NURSE') and @wardPolicy.isChargeNurse(authentication.name, #ward)")
public @interface IsChargeNurseOfWard {
}
package com.javabytechie.rostering;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.access.prepost.PreAuthorize;
// {value} is replaced with the annotation's value, e.g. @RequireRole("HR")
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('{value}')")
public @interface RequireRole {
String value();
}
package com.javabytechie.rostering;
import java.util.Map;
import org.springframework.stereotype.Component;
// Complex or data-driven rules belong in a bean, not in a long SpEL string
@Component("wardPolicy")
public class WardPolicy {
private final Map<String, String> chargeNurseByWard = Map.of("ICU", "dev", "MATERNITY", "sana");
public boolean isChargeNurse(String username, String ward) {
return username.equals(chargeNurseByWard.get(ward));
}
}
package com.javabytechie.rostering;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.annotation.AnnotationTemplateExpressionDefaults;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable()); // rostering app client, no browser cookies
return http.build();
}
// Enables {placeholders} in meta-annotations such as @RequireRole
@Bean
static AnnotationTemplateExpressionDefaults templateDefaults() {
return new AnnotationTemplateExpressionDefaults();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo staff only
return new InMemoryUserDetailsManager(
User.withUsername("meena").password(encoder.encode("meena-pass")).roles("NURSE").build(),
User.withUsername("dev").password(encoder.encode("dev-pass")).roles("NURSE", "CHARGE_NURSE").build(),
User.withUsername("sana").password(encoder.encode("sana-pass")).roles("NURSE", "CHARGE_NURSE").build(),
User.withUsername("ira").password(encoder.encode("ira-pass")).roles("HR").build());
}
}
package com.javabytechie.rostering;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RosterController {
private final ShiftSwapService swaps;
public RosterController(ShiftSwapService swaps) {
this.swaps = swaps;
}
@PostMapping("/api/swaps")
public String request(@RequestBody ShiftSwapService.SwapRequest request) {
return swaps.requestSwap(request);
}
@PostMapping("/api/wards/{ward}/swaps/{id}/approve")
public String approve(@PathVariable String ward, @PathVariable String id) {
return swaps.approve(ward, id);
}
@GetMapping("/api/reports/overtime")
public List<String> overtime() {
return swaps.overtimeReport();
}
}
package com.javabytechie.rostering;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RosterApplication {
public static void main(String[] args) {
SpringApplication.run(RosterApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- Comparing an argument with the user.
#request.requestedBy() == authentication.namecalls the record accessor on therequestargument and compares it with the logged-in username. A nurse cannot file a request in a colleague's name. - A policy bean.
@wardPolicy.isChargeNurse(...)callsWardPolicy, whose bean name is set with@Component("wardPolicy"). Real rules can query a database here, and the bean is easy to unit test. - A meta-annotation.
@IsChargeNurseOfWardcarries the full@PreAuthorizeexpression. Methods use the short, descriptive name, and the rule lives in one place. - A templated meta-annotation.
@RequireRole("HR")fills{value}intohasRole('{value}'). Templates are switched on by theAnnotationTemplateExpressionDefaultsbean, available since Spring Security 6.4. - Checks first, then work. In every case the method body runs only when the expression is true, so a denied approval leaves no trace in the roster.
6. Expected Output
$ curl -u meena:meena-pass -X POST localhost:8080/api/swaps -H 'Content-Type: application/json' -d '{"shiftId":"S-10","ward":"ICU","requestedBy":"meena"}'
HTTP/1.1 200
Swap requested for S-10 by meena
$ curl -u meena:meena-pass -X POST localhost:8080/api/swaps -H 'Content-Type: application/json' -d '{"shiftId":"S-11","ward":"ICU","requestedBy":"joseph"}'
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:45.059Z","status":403,"error":"Forbidden","path":"/api/swaps"}
$ curl -u dev:dev-pass -X POST localhost:8080/api/wards/ICU/swaps/SW-1/approve
HTTP/1.1 200
SW-1 approved on ICU
$ curl -u sana:sana-pass -X POST localhost:8080/api/wards/ICU/swaps/SW-1/approve
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:45.202Z","status":403,"error":"Forbidden","path":"/api/wards/ICU/swaps/SW-1/approve"}
$ curl -u ira:ira-pass localhost:8080/api/reports/overtime
HTTP/1.1 200
["meena: 6 h","joseph: 2 h"]
$ curl -u meena:meena-pass localhost:8080/api/reports/overtime
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:45.337Z","status":403,"error":"Forbidden","path":"/api/reports/overtime"}
Meena may request a swap for her own shift but not in Joseph's name. Dev is the ICU charge nurse and approves the ICU swap; Sana is also a charge nurse, but of maternity, so the policy bean denies her. The templated @RequireRole("HR") lets Ira read the overtime report and refuses Meena.
7. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Full SpEL: roles, arguments, current user and beans | Expressions are strings; typos are found at runtime, not compile time |
| Runs before the method, so no side effects on denial | Cannot check the returned object; use @PostAuthorize for that |
| Meta-annotations keep rules short and reusable | Only works on calls through the Spring proxy |
| Policy beans make complex rules testable | Each bean call adds work to every invocation |
8. Common Mistakes and Best Practices
- Annotation ignored. Add
@EnableMethodSecurity, and call the method on the injected bean, not onthis. #nameresolves to null. The class was compiled without-parameters. Use Spring Boot's build plugins or add@P.- Long expressions. Move anything beyond one or two conditions into a policy bean and give it a meaningful method name.
- Repeated strings. Wrap rules used on several methods in a meta-annotation.
- Checking ownership of data you have not loaded yet. If the rule depends on fields of the returned object, use @PostAuthorize, or load the object first and pass it to a policy bean.
9. Summary
@PreAuthorizeevaluates a SpEL expression before a method runs; false means 403 and no side effects.- Expressions can use roles, authorities,
authentication, method arguments (#name) and beans (@bean). - Put complex rules in a policy bean and reference it from the expression.
- Meta-annotations, including templated ones with
AnnotationTemplateExpressionDefaults, keep rules short and consistent. - Method security must be enabled with
@EnableMethodSecurity, and calls must go through the Spring proxy.
10. References
Frequently Asked Questions (FAQ)
Q1. How do I use a method parameter in @PreAuthorize?
Refer to it with # and its name, for example @PreAuthorize("#username == authentication.name"). The code must be compiled with -parameters, or the parameter must be annotated with @P("username").
Q2. How do I call a Spring bean from @PreAuthorize?
Use @beanName.method(...), for example @PreAuthorize("@wardPolicy.isChargeNurse(authentication.name, #ward)"). The bean name is the one registered in the application context.
Q3. What is the difference between @PreAuthorize and @Secured?
@PreAuthorize takes a SpEL expression that can use arguments, the current user and beans. @Secured only lists authority names and must be enabled with securedEnabled = true.
Q4. Can I put @PreAuthorize on a class?
Yes. A class-level annotation applies to all public methods of the bean; a method-level annotation on a specific method takes precedence.
Q5. What exception does @PreAuthorize throw when access is denied?
It throws AuthorizationDeniedException, a subclass of AccessDeniedException. In a web request, Spring Security turns it into 403 Forbidden.