Spring Security Annotations Explained
Spring Security annotations let you switch features on and express access rules right next to the code they protect. A single line such as @PreAuthorize("hasRole('LIBRARIAN')") on a service method replaces a manual check, and @AuthenticationPrincipal hands a controller the logged-in user without touching static helpers.
Spring Security has several families of annotations, and they differ in small but important ways: which ones need enabling, which accept expressions, and which add the ROLE_ prefix for you. This page is a reference to all of them, followed by one runnable example that uses the most important annotations side by side. Detailed tutorials for each method security annotation are linked from the tables.
1. What Are Spring Security Annotations?
They are Java annotations that Spring Security reads at startup or at call time. Configuration annotations such as @EnableMethodSecurity register infrastructure. Method security annotations such as @PreAuthorize are applied by proxies that Spring creates around your beans, as explained in method-level security. Argument annotations such as @AuthenticationPrincipal are resolved by Spring MVC, and test annotations prepare a security context for tests.
2. Why Use Annotations?
- Rules live with the code. Readers see who may call a method without opening a separate configuration file.
- They protect every caller. A service method annotated with
@PreAuthorizeis checked whether it is called from a controller, a scheduled job or another service, as long as the call goes through the Spring proxy. - They remove boilerplate. No manual
SecurityContextHolderlookups in controllers and no repeatedifchecks in services.
3. The Annotations at a Glance
3.1 Configuration Annotations
| Annotation | Purpose | Notes |
|---|---|---|
@EnableWebSecurity | Turns on web security configuration | Spring Boot applies it automatically; add it only outside Boot or for debug = true |
@EnableMethodSecurity | Turns on method security | Pre/post annotations on by default; securedEnabled and jsr250Enabled are off by default |
3.2 Method Security Annotations
| Annotation | Checks | ROLE_ prefix | Tutorial |
|---|---|---|---|
@PreAuthorize | SpEL expression before the call | Added by hasRole | @PreAuthorize |
@PostAuthorize | SpEL expression after the call, with returnObject | Added by hasRole | @PostAuthorize |
@PreFilter | Removes elements from a collection argument | - | @PreFilter |
@PostFilter | Removes elements from a returned collection | - | @PostFilter |
@Secured | List of authorities, no expressions | Not added: write ROLE_X | @Secured |
@RolesAllowed, @PermitAll, @DenyAll | Jakarta standard role lists | Added: write X | @RolesAllowed |
@HandleAuthorizationDenied | Returns a fallback instead of throwing on denial (6.3+) | - | Method-level security |
@AuthorizeReturnObject | Wraps the returned object so its own annotations are checked (6.3+) | - | - |
When choosing between the three method security families, start with @PreAuthorize: it covers everything the others do and adds expressions over arguments, the current user and other beans. @Secured and @RolesAllowed remain useful for short role lists or when code must also run on a Jakarta EE server, but mixing all three in one project makes the prefix rules hard to remember.
3.3 Controller Argument Annotations
| Annotation | Injects |
|---|---|
@AuthenticationPrincipal | The principal, usually your UserDetails; can use expression to extract a field |
@CurrentSecurityContext | The SecurityContext, or a value from it through expression |
3.4 Test Annotations (spring-security-test)
| Annotation | Sets up |
|---|---|
@WithMockUser | A fake authenticated user with given username and roles |
@WithUserDetails | A user loaded through your UserDetailsService |
@WithAnonymousUser | An anonymous user |
@WithSecurityContext | Your own factory for custom principals |
Testing is covered in detail in Spring Security testing.
4. How Method Security Annotations Are Enforced
When a check fails, the proxy throws AuthorizationDeniedException, which Spring Security turns into a 403 for a web request. Calls from one method to another inside the same class skip the proxy and therefore skip the checks.
5. A Complete Example: E-Book Lending Service
A library's e-book service uses five annotations: @PostFilter hides staff-only titles from members, @PreAuthorize lets members read only their own loans, @Secured and @RolesAllowed guard two other methods, and the controller uses @AuthenticationPrincipal and @CurrentSecurityContext. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.
package com.javabytechie.ebooks;
import java.util.ArrayList;
import java.util.List;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class EbookService {
public record Ebook(String title, String audience) {}
// Members see public titles only; librarians see everything
@PostFilter("filterObject.audience() == 'PUBLIC' or hasRole('LIBRARIAN')")
public List<Ebook> catalog() {
return new ArrayList<>(List.of( // @PostFilter needs a mutable list
new Ebook("Clean Architecture", "PUBLIC"),
new Ebook("Cataloguing Handbook", "STAFF"),
new Ebook("The Hobbit", "PUBLIC")));
}
// Expressions can use method arguments
@PreAuthorize("#member == authentication.name or hasRole('LIBRARIAN')")
public List<String> loansOf(String member) {
return List.of(member + ": The Hobbit, due 2 Dec");
}
// @Secured: full authority name, no expressions
@Secured("ROLE_MEMBER")
public String borrowingRules() {
return "Members may borrow 3 e-books for 14 days";
}
// @RolesAllowed: role name without the prefix
@RolesAllowed("LIBRARIAN")
public List<String> overdueReport() {
return List.of("priya: none", "arun: 1 overdue");
}
}
package com.javabytechie.ebooks;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EbookController {
private final EbookService service;
public EbookController(EbookService service) {
this.service = service;
}
@GetMapping("/api/me")
public Map<String, Object> me(@AuthenticationPrincipal UserDetails user,
@CurrentSecurityContext(expression = "authentication.name") String name) {
List<String> roles = user.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
return Map.of("nameFromContext", name, "principalRoles", roles);
}
@GetMapping("/api/ebooks")
public List<EbookService.Ebook> catalog() {
return service.catalog();
}
@GetMapping("/api/loans/{member}")
public List<String> loans(@PathVariable String member) {
return service.loansOf(member);
}
@GetMapping("/api/loans")
public String rules() {
return service.borrowingRules();
}
@GetMapping("/api/reports/overdue")
public List<String> overdue() {
return service.overdueReport();
}
}
package com.javabytechie.ebooks;
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.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(securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo users only
return new InMemoryUserDetailsManager(
User.withUsername("priya").password(encoder.encode("priya-pass")).roles("MEMBER").build(),
User.withUsername("leo").password(encoder.encode("leo-pass")).roles("LIBRARIAN").build());
}
}
package com.javabytechie.ebooks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EbookApplication {
public static void main(String[] args) {
SpringApplication.run(EbookApplication.class, args);
}
}
@RolesAllowed lives in the jakarta.annotation-api library. Add it if your project does not already have it; Spring Boot manages the version:
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
</dependency>
6. Step-by-Step Code Explanation
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)activates all three families. Without the two flags,@Securedand@RolesAllowedwould be ignored silently.@PostFilterruns aftercatalog()returns and removes every element for which the expression is false.filterObjectis the current element. The list must be mutable.@PreAuthorizecompares thememberargument (#member) with the logged-in username, a rule no role list can express.@Secured("ROLE_MEMBER")needs the full authority name, while@RolesAllowed("LIBRARIAN")addsROLE_itself.@AuthenticationPrincipalinjects theUserDetailscreated at login, and@CurrentSecurityContext(expression = ...)evaluates an expression against the security context, here reading the user's name. The expression result must match the parameter type; aStringor an object type works, while a primitive such asintfails at runtime.
7. Expected Output
$ curl -u priya:priya-pass localhost:8080/api/me
HTTP/1.1 200
{"principalRoles":["ROLE_MEMBER"],"nameFromContext":"priya"}
$ curl -u priya:priya-pass localhost:8080/api/ebooks
HTTP/1.1 200
[{"title":"Clean Architecture","audience":"PUBLIC"},{"title":"The Hobbit","audience":"PUBLIC"}]
$ curl -u leo:leo-pass localhost:8080/api/ebooks
HTTP/1.1 200
[{"title":"Clean Architecture","audience":"PUBLIC"},{"title":"Cataloguing Handbook","audience":"STAFF"},{"title":"The Hobbit","audience":"PUBLIC"}]
$ curl -u priya:priya-pass localhost:8080/api/loans/priya
HTTP/1.1 200
["priya: The Hobbit, due 2 Dec"]
$ curl -u priya:priya-pass localhost:8080/api/loans/leo
HTTP/1.1 403
{"timestamp":"2026-11-18T12:13:43.540Z","status":403,"error":"Forbidden","path":"/api/loans/leo"}
$ curl -u priya:priya-pass localhost:8080/api/loans
HTTP/1.1 200
Members may borrow 3 e-books for 14 days
$ curl -u leo:leo-pass localhost:8080/api/loans
HTTP/1.1 403
{"timestamp":"2026-11-18T12:13:43.674Z","status":403,"error":"Forbidden","path":"/api/loans"}
$ curl -u priya:priya-pass localhost:8080/api/reports/overdue
HTTP/1.1 403
{"timestamp":"2026-11-18T12:13:43.740Z","status":403,"error":"Forbidden","path":"/api/reports/overdue"}
$ curl -u leo:leo-pass localhost:8080/api/reports/overdue
HTTP/1.1 200
["priya: none","arun: 1 overdue"]
The first response shows the name read from the security context and the roles held by her UserDetails principal. Her catalogue hides the staff-only title, while Leo sees all three. Priya can read her own loans but not Leo's. The borrowing rules are @Secured("ROLE_MEMBER"), so Leo, a librarian without the member role, gets 403; the overdue report is the reverse.
8. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Rules visible next to the protected code | Rules spread across many classes; harder to review in one place |
| Protects service methods for every caller | Self-invocation and private methods bypass the proxy |
| SpEL expressions can use arguments and return values | Expression strings are not checked by the compiler |
Standard @RolesAllowed eases migration from Jakarta EE | Three families with different prefix rules can confuse a team |
9. Common Mistakes and Best Practices
- Annotations that do nothing. Missing
@EnableMethodSecurity, or missingsecuredEnabledorjsr250Enabled, means no checks at all. - Wrong prefix.
@Secured("MEMBER")never matches;@RolesAllowed("ROLE_MEMBER")is unnecessary. - Using the old
@EnableGlobalMethodSecurity. It is deprecated; use@EnableMethodSecurity. - Immutable collections with filter annotations.
@PostFilterand@PreFilterfail onList.of(...). - Pick one style per project. Prefer
@PreAuthorizefor new code; use@Securedor@RolesAllowedonly for simple role lists or compatibility.
10. Summary
@EnableMethodSecurityturns on method security;@Securedand@RolesAllowedneed extra flags.@PreAuthorizeand@PostAuthorizeaccept SpEL;@PreFilterand@PostFilterfilter collections.@Securedtakes full authority names,@RolesAllowedaddsROLE_for you.@AuthenticationPrincipaland@CurrentSecurityContextinject the user into controllers.- Test annotations such as
@WithMockUserset up a security context in tests.
11. References
Frequently Asked Questions (FAQ)
Q1. Which annotation enables method security in Spring Boot 3 and 4?
@EnableMethodSecurity on a configuration class. It replaces the deprecated @EnableGlobalMethodSecurity and enables the pre/post annotations by default.
Q2. What is the difference between @Secured and @RolesAllowed?
Both list roles. @Secured is Spring's own and expects full authority names such as ROLE_ADMIN; @RolesAllowed is the Jakarta standard and adds the ROLE_ prefix for you. Enable them with securedEnabled and jsr250Enabled.
Q3. Do I need @EnableWebSecurity in Spring Boot?
No. Spring Boot applies it automatically when Spring Security is on the classpath. You can still add it, for example to use @EnableWebSecurity(debug = true) while troubleshooting.
Q4. How do I get the logged-in user in a controller?
Add a parameter annotated with @AuthenticationPrincipal, typed as your principal class or UserDetails. @CurrentSecurityContext gives access to the whole security context.
Q5. Why are my security annotations ignored?
Common causes are a missing @EnableMethodSecurity, a disabled annotation family, calling the method from within the same class, a private method, or an object created with new instead of injected by Spring.