00:00

@PreAuthorize Annotation in Spring Security

Last updated:

@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

Evaluation of a @PreAuthorize expressionThe proxy builds an evaluation context with the Authentication, method arguments by name and access to Spring beans, evaluates the SpEL expression, and either calls the method or throws AuthorizationDeniedException. Call through proxy approve("ICU", "SW-1") authentication, principal #ward, #id (method arguments) @wardPolicy (Spring beans) Evaluate SpEL true: run method false: 403 nothing runs
Figure 1: arguments, the current user and Spring beans are all available to the expression.

3.1 The Expression Vocabulary

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

5. Step-by-Step Code Explanation

  1. Comparing an argument with the user. #request.requestedBy() == authentication.name calls the record accessor on the request argument and compares it with the logged-in username. A nurse cannot file a request in a colleague's name.
  2. A policy bean. @wardPolicy.isChargeNurse(...) calls WardPolicy, whose bean name is set with @Component("wardPolicy"). Real rules can query a database here, and the bean is easy to unit test.
  3. A meta-annotation. @IsChargeNurseOfWard carries the full @PreAuthorize expression. Methods use the short, descriptive name, and the rule lives in one place.
  4. A templated meta-annotation. @RequireRole("HR") fills {value} into hasRole('{value}'). Templates are switched on by the AnnotationTemplateExpressionDefaults bean, available since Spring Security 6.4.
  5. 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

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

AdvantagesLimitations
Full SpEL: roles, arguments, current user and beansExpressions are strings; typos are found at runtime, not compile time
Runs before the method, so no side effects on denialCannot check the returned object; use @PostAuthorize for that
Meta-annotations keep rules short and reusableOnly works on calls through the Spring proxy
Policy beans make complex rules testableEach 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 on this.
  • #name resolves 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

  • @PreAuthorize evaluates 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