00:00

Spring Security Annotations Explained

Last updated:

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 @PreAuthorize is 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 SecurityContextHolder lookups in controllers and no repeated if checks in services.

3. The Annotations at a Glance

3.1 Configuration Annotations

AnnotationPurposeNotes
@EnableWebSecurityTurns on web security configurationSpring Boot applies it automatically; add it only outside Boot or for debug = true
@EnableMethodSecurityTurns on method securityPre/post annotations on by default; securedEnabled and jsr250Enabled are off by default

3.2 Method Security Annotations

AnnotationChecksROLE_ prefixTutorial
@PreAuthorizeSpEL expression before the callAdded by hasRole@PreAuthorize
@PostAuthorizeSpEL expression after the call, with returnObjectAdded by hasRole@PostAuthorize
@PreFilterRemoves elements from a collection argument-@PreFilter
@PostFilterRemoves elements from a returned collection-@PostFilter
@SecuredList of authorities, no expressionsNot added: write ROLE_X@Secured
@RolesAllowed, @PermitAll, @DenyAllJakarta standard role listsAdded: write X@RolesAllowed
@HandleAuthorizationDeniedReturns a fallback instead of throwing on denial (6.3+)-Method-level security
@AuthorizeReturnObjectWraps 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

AnnotationInjects
@AuthenticationPrincipalThe principal, usually your UserDetails; can use expression to extract a field
@CurrentSecurityContextThe SecurityContext, or a value from it through expression

3.4 Test Annotations (spring-security-test)

AnnotationSets up
@WithMockUserA fake authenticated user with given username and roles
@WithUserDetailsA user loaded through your UserDetailsService
@WithAnonymousUserAn anonymous user
@WithSecurityContextYour own factory for custom principals

Testing is covered in detail in Spring Security testing.

4. How Method Security Annotations Are Enforced

Method security proxy around an annotated beanThe controller calls a Spring proxy. The proxy evaluates @PreAuthorize, @Secured or @RolesAllowed before the real service runs, then @PostAuthorize and @PostFilter after it returns. Controller calls the service Spring proxy pre checks / post checks Real EbookService your method body call result @PreAuthorize, @Secured, @RolesAllowed run before; @PostAuthorize, @PostFilter after
Figure 1: the proxy checks "pre" annotations before the call and "post" annotations after it.

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");
    }
}

@RolesAllowed lives in the jakarta.annotation-api library. Add it if your project does not already have it; Spring Boot manages the version:

pom.xml (extra dependency)
<dependency>
    <groupId>jakarta.annotation</groupId>
    <artifactId>jakarta.annotation-api</artifactId>
</dependency>

6. Step-by-Step Code Explanation

  1. @EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true) activates all three families. Without the two flags, @Secured and @RolesAllowed would be ignored silently.
  2. @PostFilter runs after catalog() returns and removes every element for which the expression is false. filterObject is the current element. The list must be mutable.
  3. @PreAuthorize compares the member argument (#member) with the logged-in username, a rule no role list can express.
  4. @Secured("ROLE_MEMBER") needs the full authority name, while @RolesAllowed("LIBRARIAN") adds ROLE_ itself.
  5. @AuthenticationPrincipal injects the UserDetails created 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; a String or an object type works, while a primitive such as int fails at runtime.

7. Expected Output

Terminal
$ 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

AdvantagesLimitations
Rules visible next to the protected codeRules spread across many classes; harder to review in one place
Protects service methods for every callerSelf-invocation and private methods bypass the proxy
SpEL expressions can use arguments and return valuesExpression strings are not checked by the compiler
Standard @RolesAllowed eases migration from Jakarta EEThree families with different prefix rules can confuse a team

9. Common Mistakes and Best Practices

  • Annotations that do nothing. Missing @EnableMethodSecurity, or missing securedEnabled or jsr250Enabled, 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. @PostFilter and @PreFilter fail on List.of(...).
  • Pick one style per project. Prefer @PreAuthorize for new code; use @Secured or @RolesAllowed only for simple role lists or compatibility.

10. Summary

  • @EnableMethodSecurity turns on method security; @Secured and @RolesAllowed need extra flags.
  • @PreAuthorize and @PostAuthorize accept SpEL; @PreFilter and @PostFilter filter collections.
  • @Secured takes full authority names, @RolesAllowed adds ROLE_ for you.
  • @AuthenticationPrincipal and @CurrentSecurityContext inject the user into controllers.
  • Test annotations such as @WithMockUser set up a security context in tests.

11. References