Annotation-Based Authorization
@PreAuthorize, @PostAuthorize, @Secured, @RolesAllowed, SpEL-based rules
- Protect service methods with @PreAuthorize expressions
- Filter return values with @PostFilter
- Understand the difference between @Secured and @PreAuthorize
Table of Contents
- Overview — Two Levels of Authorization in Spring Security
- Why Annotation-Based Authorization?
- Authentication Object & Granted Authorities
- Database Model — Users, Roles & Permissions
- Implementing UserDetailsService — Loading Roles and Permissions
- Enabling Annotation-Based Security
- @PreAuthorize — Authorization Before Method Execution
- @PostAuthorize — Authorization After Method Execution
- hasRole() vs hasAuthority() — Deep Dive
- Spring Expression Language (SpEL) in Authorization Annotations
- Internal Mechanics — How @PreAuthorize is Intercepted
- Accessing the Authentication Object in Annotations
- Complete Working Example — End to End
- Common Mistakes
- Best Practices
- Interview Notes
- Summary
- Practice Questions
1. Overview Two Levels of Authorization in Spring Security
Spring Security supports two distinct places where you can implement authorization logic:
Level 1: Filter-Layer Authorization (SecurityFilterChain)
1@Bean2public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {3 http.authorizeHttpRequests(auth -> auth4 .requestMatchers("/api/orders").hasRole("USER")5 .requestMatchers("/api/admin").hasRole("ADMIN")6 .anyRequest().authenticated()7 );8 return http.build();9}Problem with this approach at scale:
- Every single API endpoint must be listed here
- Large applications can have hundreds of APIs
- This file becomes a maintenance nightmare
- Security config is decoupled from the actual endpoint definition — hard to reason about
Level 2: Annotation-Based Authorization (@PreAuthorize / @PostAuthorize)
1@GetMapping("/api/orders")2@PreAuthorize("hasRole('USER') and hasAuthority('ORDER_READ')")3public ResponseEntity<List<Order>> getOrders() { ... }Advantages:
- Authorization is defined right next to the endpoint — easy to read and maintain
- Scales naturally — each controller owns its own authorization rules
- Supports fine-grained, granular permissions beyond just roles
- Supports post-execution logic using the return value
2. Why Annotation-Based Authorization?
The Scalability Problem
Consider an enterprise application with 200+ REST endpoints:
1// This becomes unmanageable at scale:2http.authorizeHttpRequests(auth -> auth3 .requestMatchers("/api/orders/read").hasRole("USER")4 .requestMatchers("/api/orders/create").hasRole("MANAGER")5 .requestMatchers("/api/orders/delete").hasRole("ADMIN")6 .requestMatchers("/api/sales/read").hasRole("USER")7 .requestMatchers("/api/sales/create").hasAuthority("SALES_CREATE")8 .requestMatchers("/api/inventory/read").hasRole("USER")9 // ... 190 more entries10);Problems:
- All authorization logic is in one place, disconnected from the code it governs
- Adding a new API requires editing the security config file
- Impossible to enforce per-field or return-value-based authorization
- Testing is complex because authorization is centralized
The Annotation Solution
1// OrderController.java — authorization lives with the endpoint:2@RestController3public class OrderController {4
5 @GetMapping("/api/orders")6 @PreAuthorize("hasRole('USER') and hasAuthority('ORDER_READ')")7 public String getOrders() { ... }8
9 @DeleteMapping("/api/orders/{id}")10 @PreAuthorize("hasRole('ADMIN')")11 public String deleteOrder(@PathVariable Long id) { ... }12}Authorization intent is co-located with the business code. Any developer reading this file immediately understands who can call each method.
3. Authentication Object & Granted Authorities
Understanding this is critical — it's the foundation of annotation-based authorization.
The Authentication Object
When a user successfully authenticates (via Basic Auth, JWT, OAuth, etc.), Spring Security creates an Authentication object and stores it in the SecurityContextHolder. This object travels through the entire request lifecycle — including all the way to the controller.
Structure of the Authentication Object
1public interface Authentication extends Principal, Serializable {2 Collection<? extends GrantedAuthority> getAuthorities(); // ← ROLES + PERMISSIONS3 Object getCredentials(); // password (cleared after auth)4 Object getPrincipal(); // UserDetails object (your User entity)5 boolean isAuthenticated();6}Granted Authorities The Single List
getAuthorities(). There is no structural difference between a role and an authority inside the framework. The only distinction is a naming convention: roles are prefixed with ROLE_.1Authentication.getAuthorities() =2[3 "ROLE_USER", ← Role (note the ROLE_ prefix)4 "ORDER_READ", ← Permission/Authority (no prefix)5 "SALES_CREATE" ← Permission/Authority (no prefix)6]This list is populated from your getAuthorities() implementation in UserDetails. How you populate it determines what gets checked by hasRole() and hasAuthority().
4. Database Model Users, Roles & Permissions
To implement granular permission control, a two-table model is used:
Table Design
1-- Table 1: user_login2-- Stores the user's top-level role (e.g., USER, ADMIN)3CREATE TABLE user_login (4 id BIGINT PRIMARY KEY AUTO_INCREMENT,5 username VARCHAR(255) UNIQUE NOT NULL,6 password VARCHAR(255) NOT NULL,7 role VARCHAR(50) NOT NULL -- e.g., 'USER', 'ADMIN'8);9
10-- Table 2: user_permission11-- Stores granular permissions for each user (one-to-many)12CREATE TABLE user_permission (13 id BIGINT PRIMARY KEY AUTO_INCREMENT,14 user_id BIGINT NOT NULL,15 name VARCHAR(100) NOT NULL, -- e.g., 'ORDER_READ', 'SALES_CREATE'16 FOREIGN KEY (user_id) REFERENCES user_login(id)17);Entity Classes
1@Entity2@Table(name = "user_login")3public class UserLogin {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String username;10 private String password;11 private String role; // High-level role: "USER" or "ADMIN"12
13 // One user → many permissions14 @OneToMany(mappedBy = "userLogin", fetch = FetchType.EAGER)15 private List<UserPermission> permissions;16
17 // Getters and setters...18}19
20@Entity21@Table(name = "user_permission")22public class UserPermission {23
24 @Id25 @GeneratedValue(strategy = GenerationType.IDENTITY)26 private Long id;27
28 private String name; // Granular permission: "ORDER_READ", "SALES_CREATE"29
30 @ManyToOne31 @JoinColumn(name = "user_id")32 private UserLogin userLogin;33
34 // Getters and setters...35}Sample Data
1user_login table:2+----+----------+----------+------+3| id | username | password | role |4+----+----------+----------+------+5| 1 | shreyans | $2a$... | USER |6+----+----------+----------+------+7
8user_permission table:9+----+---------+------------+10| id | user_id | name |11+----+---------+------------+12| 1 | 1 | ORDER_READ |13+----+---------+------------+The user shreyans has:
- Role:
USER(high-level) - Permission:
ORDER_READ(granular) - No
SALES_READpermission → cannot access sales endpoints
5. Implementing UserDetailsService Loading Roles and Permissions
This is where roles and permissions are assembled into the GrantedAuthority list that Spring Security uses for all authorization checks.
1@Service2public class UserEntityService implements UserDetailsService {3
4 @Autowired5 private UserLoginRepository userLoginRepository;6
7 @Override8 public UserDetails loadUserByUsername(String username)9 throws UsernameNotFoundException {10
11 UserLogin user = userLoginRepository.findByUsername(username)12 .orElseThrow(() ->13 new UsernameNotFoundException("User not found: " + username));14
15 return new User(16 user.getUsername(),17 user.getPassword(),18 getAuthorities(user) // ← Critical: build the authority list19 );20 }21
22 private Collection<GrantedAuthority> getAuthorities(UserLogin user) {23 List<GrantedAuthority> authorities = new ArrayList<>();24
25 // 1. Add the high-level role (Spring expects ROLE_ prefix)26 authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));27 // Result: "ROLE_USER"28
29 // 2. Add all granular permissions30 for (UserPermission permission : user.getPermissions()) {31 authorities.add(new SimpleGrantedAuthority(permission.getName()));32 // Result: "ORDER_READ", "SALES_CREATE", etc.33 }34
35 return authorities;36 }37}What the Final List Contains
For the user shreyans (role=USER, permissions=[ORDER_READ]):
1getAuthorities() returns:2[3 SimpleGrantedAuthority("ROLE_USER"),4 SimpleGrantedAuthority("ORDER_READ")5]This list is what every hasRole() and hasAuthority() check runs against.
ROLE_ prefix when building the SimpleGrantedAuthority. hasRole('USER') in SpEL will also add ROLE_ automatically before checking — so hasRole('USER') checks for ROLE_USER in the list. That's why you must store it as ROLE_USER.6. Enabling Annotation-Based Security
Before @PreAuthorize and @PostAuthorize will work, you must explicitly enable method-level security in your security configuration class.
1@Configuration2@EnableWebSecurity3@EnableMethodSecurity(prePostEnabled = true) // ← THIS IS REQUIRED4public class SecurityConfig {5
6 @Bean7 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {8 http9 .csrf(csrf -> csrf.disable())10 .authorizeHttpRequests(auth -> auth11 .anyRequest().authenticated() // All requests must be authenticated12 )13 .httpBasic(Customizer.withDefaults()); // Using Basic Auth for testing14
15 return http.build();16 }17}What `@EnableMethodSecurity(prePostEnabled = true)` Does
Without this annotation, Spring Security ignores @PreAuthorize and @PostAuthorize annotations entirely. The methods execute without any authorization check.
With prePostEnabled = true, Spring registers the necessary AOP interceptors that intercept annotated methods before/after execution.
@EnableGlobalMethodSecurity(prePostEnabled = true). In Spring Boot 3.x / Spring Security 6.x, the replacement is @EnableMethodSecurity(prePostEnabled = true). The prePostEnabled = true is actually the default in @EnableMethodSecurity, but it is good practice to be explicit.7. @PreAuthorize Authorization Before Method Execution
Overview
@PreAuthorize runs the authorization check before the annotated method body executes. If the check fails, the method is never called — a 403 Forbidden (or AccessDeniedException) is returned immediately.
Syntax
1@PreAuthorize("SpEL expression that returns boolean")2public ReturnType methodName(params) { ... }Example: Role + Permission Check
1@RestController2@RequestMapping("/api")3public class OrderController {4
5 // Requires ROLE_USER AND ORDER_READ permission6 @GetMapping("/orders")7 @PreAuthorize("hasRole('USER') and hasAuthority('ORDER_READ')")8 public ResponseEntity<String> getAllOrders() {9 return ResponseEntity.ok("All orders have been fetched successfully.");10 }11}1@RestController2@RequestMapping("/api")3public class SalesController {4
5 // Requires SALES_READ permission (regardless of role)6 @GetMapping("/sales")7 @PreAuthorize("hasAuthority('SALES_READ')")8 public ResponseEntity<String> getAllSales() {9 return ResponseEntity.ok("All sales have been fetched successfully.");10 }11}Testing the Behavior
Setup:
- User
shreyanshas:ROLE_USER,ORDER_READ
| Request | Endpoint | Result | Reason |
|---|---|---|---|
shreyans calls /api/orders | GET /api/orders | ✅ 200 OK | Has ROLE_USER AND ORDER_READ — both conditions met |
shreyans calls /api/sales | GET /api/sales | ❌ 403 Forbidden | Does NOT have SALES_READ permission |
Execution Flow for @PreAuthorize
8. @PostAuthorize Authorization After Method Execution
Overview
@PostAuthorize runs the authorization check after the annotated method executes but before the response is sent to the client. The method's return value is accessible via the special keyword returnObject.
When to Use @PostAuthorize
Use @PostAuthorize when the authorization decision depends on data that only exists after the business logic runs — for example, when you need to verify that the returned data belongs to the requesting user.
Syntax
1@PostAuthorize("SpEL expression using returnObject")2public SomeDTO methodName(params) { ... }The `returnObject` Keyword
Inside a @PostAuthorize expression, returnObject is a special variable that holds the method's return value. Spring Security automatically type-casts it — you don't need to cast it manually.
1@PostAuthorize("returnObject.userId == authentication.principal.id")2// returnObject is typed as the method's return type (OrderDTO in this case)Example: User Can Only Access Their Own Data
Scenario: Both User A (id=1) and User B (id=2) have ROLE_USER and ORDER_READ. But User B should not be able to read User A's orders.
1@Entity2public class OrderDTO {3 private Long orderId;4 private Long userId; // Which user this order belongs to5 private String details;6 // Getters and setters...7}1@RestController2@RequestMapping("/api")3public class OrderController {4
5 @GetMapping("/orders")6 @PreAuthorize("hasRole('USER') and hasAuthority('ORDER_READ')")7 @PostAuthorize("returnObject.userId == authentication.principal.id")8 public OrderDTO getOrder() {9
10 // Business logic runs first (DB fetch, computation, etc.)11 // For demonstration, hardcoded to return order belonging to user ID 112 OrderDTO dto = new OrderDTO();13 dto.setOrderId(101L);14 dto.setUserId(1L); // This order belongs to user with ID = 115 dto.setDetails("Order details here");16
17 return dto;18 // AFTER this returns, @PostAuthorize checks the condition19 }20}Testing the Behavior
Setup:
- User A:
id=1,username=auser,ROLE_USER,ORDER_READ - User B:
id=2,username=buser,ROLE_USER,ORDER_READ
| Caller | returnObject.userId | authentication.principal.id | Result |
|---|---|---|---|
| User A (id=1) | 1 | 1 | 1 == 1 → ✅ 200 OK |
| User B (id=2) | 1 | 2 | 1 == 2 → ❌ 403 Forbidden |
User B's request:
- Passes
@PreAuthorize(hasROLE_USERandORDER_READ) ✅ - The method executes (DB is queried, OrderDTO is built)
@PostAuthorizeevaluates:returnObject.userId (1) == authentication.principal.id (2)→false- Response is blocked → 403 Forbidden
@PostAuthorize, the business logic always runs, even if authorization will ultimately fail. If the method has side effects (writes to DB, sends emails, etc.), those side effects happen before the authorization check blocks the response. Use @PreAuthorize for mutation operations. Reserve @PostAuthorize for read operations where the decision depends on the returned data.Execution Flow for @PostAuthorize
9. hasRole() vs hasAuthority() Deep Dive
This is a very commonly misunderstood topic. The key insight: at the code level, they are the same.
Conceptual Distinction
hasRole() | hasAuthority() | |
|---|---|---|
| Intended for | High-level role distinction | Granular permission distinction |
| Example usage | hasRole('USER'), hasRole('ADMIN') | hasAuthority('ORDER_READ'), hasAuthority('SALES_CREATE') |
| Prefix behavior | Automatically prepends ROLE_ | No prefix added — used as-is |
| What gets checked | ROLE_USER in authorities list | ORDER_READ in authorities list |
Internal Code They Call the Same Method
1// SecurityExpressionRoot.java (Spring Security source code)2
3public boolean hasAuthority(String authority) {4 return hasAnyAuthority(authority); // calls hasAnyAuthority5}6
7public boolean hasAnyAuthority(String... authorities) {8 return hasAnyAuthorityName(null, authorities); // no prefix added9}10
11public boolean hasRole(String role) {12 return hasAnyRole(role); // calls hasAnyRole13}14
15public boolean hasAnyRole(String... roles) {16 return hasAnyAuthorityName(this.defaultRolePrefix, roles);17 // ↑ this.defaultRolePrefix = "ROLE_"18}19
20// The single unified method both paths lead to:21private boolean hasAnyAuthorityName(String prefix, String... roles) {22 Set<String> roleSet = getAuthoritySet(); // Get the flat list of granted authorities23 for (String role : roles) {24 String defaultedRole = getRoleWithDefaultPrefix(prefix, role);25 // For hasRole: defaultedRole = "ROLE_" + role26 // For hasAuthority: defaultedRole = role (prefix is null)27 if (roleSet.contains(defaultedRole)) {28 return true;29 }30 }31 return false;32}Visual Comparison
Practical Rule
1// Convention: use hasRole for top-level access control2@PreAuthorize("hasRole('ADMIN')") // checks for ROLE_ADMIN in list3
4// Convention: use hasAuthority for granular permissions5@PreAuthorize("hasAuthority('ORDER_READ')") // checks for ORDER_READ in list6
7// Combining both:8@PreAuthorize("hasRole('USER') and hasAuthority('ORDER_READ')")ROLE_USER in hasRole(). Spring Security adds the ROLE_ prefix automatically. But in hasAuthority(), whatever string you write is checked as-is with no modification.10. Spring Expression Language (SpEL) in Authorization Annotations
The strings inside @PreAuthorize and @PostAuthorize are Spring Expression Language (SpEL) expressions. They are evaluated at runtime as boolean expressions.
Available Built-in Security Expressions
| Expression | Description | Example |
|---|---|---|
hasRole('ROLE') | User has the specified role | hasRole('ADMIN') |
hasAnyRole('R1','R2') | User has any of the specified roles | hasAnyRole('USER','ADMIN') |
hasAuthority('AUTH') | User has the specified authority/permission | hasAuthority('ORDER_READ') |
hasAnyAuthority('A1','A2') | User has any of the specified authorities | hasAnyAuthority('ORDER_READ','SALES_READ') |
isAuthenticated() | User is authenticated | isAuthenticated() |
isAnonymous() | User is not authenticated | isAnonymous() |
permitAll | Always allow | permitAll |
denyAll | Always deny | denyAll |
authentication | The Authentication object | authentication.name |
principal | The principal (UserDetails) | principal.id |
returnObject | The method's return value (@PostAuthorize only) | returnObject.userId |
#paramName | A method parameter | #id == authentication.principal.id |
Logical Operators
1// AND — both conditions must be true2@PreAuthorize("hasRole('USER') and hasAuthority('ORDER_READ')")3
4// OR — at least one condition must be true5@PreAuthorize("hasRole('ADMIN') or hasAuthority('ORDER_DELETE')")6
7// NOT — condition must be false8@PreAuthorize("not hasRole('GUEST')")9
10// Combining multiple11@PreAuthorize("(hasRole('USER') or hasRole('MANAGER')) and hasAuthority('ORDER_READ')")Relational Operators with Method Parameters
You can reference method parameters in SpEL using #parameterName syntax:
1@GetMapping("/user/{id}")2@PreAuthorize("#id == authentication.principal.id")3public UserDTO getUserById(@PathVariable Long id) {4 // Only allows the user to fetch their OWN profile5 // e.g., user with id=2 cannot call /user/16 return userService.findById(id);7}Explanation:
#id→ refers to the@PathVariable Long idmethod parameterauthentication.principal.id→ the ID of the currently authenticated user- If they don't match → 403 Forbidden (user is trying to fetch someone else's data)
Comparing #id (PreAuthorize) vs returnObject (PostAuthorize)
| Technique | Annotation | When to Use |
|---|---|---|
#paramName | @PreAuthorize | When the parameter itself is enough to make the decision (before DB call) |
returnObject | @PostAuthorize | When you need the fetched data (after DB call) to make the decision |
1// PreAuthorize with parameter — efficient (no method call if check fails)2@GetMapping("/user/{id}")3@PreAuthorize("#id == authentication.principal.id")4public UserDTO getUser(@PathVariable Long id) { ... }5
6// PostAuthorize with returnObject — method runs first, then check7@GetMapping("/orders")8@PostAuthorize("returnObject.userId == authentication.principal.id")9public OrderDTO getOrder() { ... }11. Internal Mechanics How @PreAuthorize is Intercepted
Understanding the internals is important for deep interviews and for debugging.
The Interceptor Architecture
Spring Security uses AOP (Aspect-Oriented Programming) interceptors to intercept method calls annotated with @PreAuthorize and @PostAuthorize.
| Annotation | Interceptor Class |
|---|---|
@PreAuthorize | AuthorizationManagerBeforeMethodInterceptor |
@PostAuthorize | AuthorizationManagerAfterMethodInterceptor |
These interceptors are registered automatically when @EnableMethodSecurity(prePostEnabled = true) is set.
Step-by-Step: What Happens When @PreAuthorize is Evaluated
SpEL Abstract Syntax Tree (AST)
When Spring parses "hasRole('USER') and hasAuthority('ORDER_READ')", it builds a tree:
1 AND (OpAnd)2 / \3hasRole('USER') hasAuthority('ORDER_READ')4[MethodReference] [MethodReference]For a more complex expression like "(hasRole('USER') or hasRole('ADMIN')) and hasAuthority('ORDER_READ')":
1 AND2 / \3 OR hasAuthority('ORDER_READ')4 / \5hasRole hasRole6('USER') ('ADMIN')The resolver:
- Evaluates the OR subtree (left of AND)
- Evaluates
hasAuthority(right of AND) - Applies AND to the results
The recursion handles arbitrarily complex expressions automatically.
How the Interceptor Accesses the Authentication Object
1// Inside AuthorizationManagerBeforeMethodInterceptor (Spring Security source):2public Object invoke(MethodInvocation invocation) throws Throwable {3
4 // Fetch the Authentication object from SecurityContextHolder5 // This was populated by the authentication filter earlier in the request lifecycle6 Authentication authentication =7 SecurityContextHolder.getContext().getAuthentication();8
9 // Evaluate the SpEL expression with access to:10 // - authentication object11 // - method parameters12 // - target object13 AuthorizationDecision decision = authorizationManager.check(14 () -> authentication, invocation15 );16
17 if (decision != null && !decision.isGranted()) {18 throw new AccessDeniedException("Access Denied");19 }20
21 // If granted, proceed with the actual method call22 return invocation.proceed();23}12. Accessing the Authentication Object in Annotations
Both @PreAuthorize and @PostAuthorize give you full access to the Authentication object via the authentication keyword in SpEL.
Accessing Authentication Fields
1// authentication.name → username string2@PreAuthorize("authentication.name == 'shreyans'")3
4// authentication.principal → the UserDetails object (your User entity)5@PreAuthorize("authentication.principal.id == #userId")6
7// authentication.authorities → collection of granted authorities8// (rarely used directly in SpEL — use hasRole/hasAuthority instead)Using principal.id for Row-Level Security
This is the most important real-world use case — ensuring a user can only access their own data:
1@RestController2@RequestMapping("/api/user")3public class UserController {4
5 @GetMapping("/{id}")6 @PreAuthorize("#id == authentication.principal.id")7 public UserDTO getUserById(@PathVariable Long id) {8 // User A (id=1) can call /api/user/1 ✅9 // User A (id=1) cannot call /api/user/2 ❌ → 40310 return userService.findById(id);11 }12}authentication.principal.id to work, your UserDetails implementation (or the User object returned by loadUserByUsername) must expose an id field. If you're using Spring Security's built-in User class (which only has username, password, authorities), you'll need a custom UserDetails implementation that includes id.Custom UserDetails with ID
1// Custom UserDetails implementation2public class CustomUserDetails implements UserDetails {3
4 private Long id; // ← Exposed for authentication.principal.id5 private String username;6 private String password;7 private Collection<? extends GrantedAuthority> authorities;8
9 public CustomUserDetails(UserLogin user,10 Collection<? extends GrantedAuthority> authorities) {11 this.id = user.getId();12 this.username = user.getUsername();13 this.password = user.getPassword();14 this.authorities = authorities;15 }16
17 public Long getId() { return id; } // ← SpEL accesses this via .id18
19 @Override20 public String getUsername() { return username; }21
22 @Override23 public String getPassword() { return password; }24
25 @Override26 public Collection<? extends GrantedAuthority> getAuthorities() {27 return authorities;28 }29
30 // isAccountNonExpired, isAccountNonLocked, isCredentialsNonExpired,31 // isEnabled — return true for simplicity32}13. Complete Working Example End to End
This section ties everything together with a complete, runnable example.
Project Structure
1src/main/java/com/example/security/2├── config/3│ └── SecurityConfig.java4├── controller/5│ ├── OrderController.java6│ ├── SalesController.java7│ └── UserController.java8├── entity/9│ ├── UserLogin.java10│ └── UserPermission.java11├── dto/12│ └── OrderDTO.java13├── repository/14│ └── UserLoginRepository.java15└── service/16 └── UserEntityService.javaSecurityConfig.java
1@Configuration2@EnableWebSecurity3@EnableMethodSecurity(prePostEnabled = true) // Enable @PreAuthorize and @PostAuthorize4public class SecurityConfig {5
6 @Autowired7 private UserEntityService userEntityService;8
9 @Bean10 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {11 http12 .csrf(csrf -> csrf.disable())13 .authorizeHttpRequests(auth -> auth14 .anyRequest().authenticated()15 )16 .httpBasic(Customizer.withDefaults()) // Basic auth for testing17 .userDetailsService(userEntityService);18
19 return http.build();20 }21
22 @Bean23 public PasswordEncoder passwordEncoder() {24 return new BCryptPasswordEncoder();25 }26}UserEntityService.java (UserDetailsService)
1@Service2public class UserEntityService implements UserDetailsService {3
4 @Autowired5 private UserLoginRepository repository;6
7 @Override8 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {9 UserLogin user = repository.findByUsername(username)10 .orElseThrow(() ->11 new UsernameNotFoundException("User not found: " + username));12
13 return new CustomUserDetails(user, getAuthorities(user));14 }15
16 private Collection<GrantedAuthority> getAuthorities(UserLogin user) {17 List<GrantedAuthority> authorities = new ArrayList<>();18
19 // Add role with ROLE_ prefix20 authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));21
22 // Add all granular permissions23 user.getPermissions().forEach(p ->24 authorities.add(new SimpleGrantedAuthority(p.getName()))25 );26
27 return authorities;28 }29}OrderController.java
1@RestController2@RequestMapping("/api")3public class OrderController {4
5 // Requires ROLE_USER AND ORDER_READ6 @GetMapping("/orders")7 @PreAuthorize("hasRole('USER') and hasAuthority('ORDER_READ')")8 public ResponseEntity<String> getAllOrders() {9 return ResponseEntity.ok("All orders have been fetched successfully.");10 }11
12 // Only allows user to fetch their OWN orders (using path variable check)13 @GetMapping("/orders/user/{userId}")14 @PreAuthorize("#userId == authentication.principal.id")15 public ResponseEntity<String> getOrdersByUser(@PathVariable Long userId) {16 return ResponseEntity.ok("Orders for user " + userId);17 }18
19 // PostAuthorize: check returned data belongs to caller20 @GetMapping("/order/latest")21 @PreAuthorize("hasRole('USER') and hasAuthority('ORDER_READ')")22 @PostAuthorize("returnObject.body.userId == authentication.principal.id")23 public ResponseEntity<OrderDTO> getLatestOrder() {24 // Simulating DB fetch — in real app, this would query the DB25 OrderDTO dto = new OrderDTO();26 dto.setOrderId(101L);27 dto.setUserId(1L); // This order belongs to user ID 128 return ResponseEntity.ok(dto);29 }30}SalesController.java
1@RestController2@RequestMapping("/api")3public class SalesController {4
5 // Requires SALES_READ permission (regardless of role)6 @GetMapping("/sales")7 @PreAuthorize("hasAuthority('SALES_READ')")8 public ResponseEntity<String> getAllSales() {9 return ResponseEntity.ok("All sales have been fetched successfully.");10 }11}UserController.java (Create User No Auth Required)
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @Autowired6 private UserLoginRepository repository;7
8 @Autowired9 private PasswordEncoder passwordEncoder;10
11 @PostMapping("/user")12 public ResponseEntity<String> createUser(@RequestBody CreateUserRequest request) {13 UserLogin user = new UserLogin();14 user.setUsername(request.getUsername());15 user.setPassword(passwordEncoder.encode(request.getPassword()));16 user.setRole(request.getRole());17
18 // Create permission entities19 List<UserPermission> permissions = request.getPermissions().stream()20 .map(p -> {21 UserPermission perm = new UserPermission();22 perm.setName(p);23 perm.setUserLogin(user);24 return perm;25 })26 .collect(Collectors.toList());27
28 user.setPermissions(permissions);29 repository.save(user);30
31 return ResponseEntity.ok("User created successfully.");32 }33}Test Scenarios
Create Users via API
1POST /api/user2Content-Type: application/json3
4{5 "username": "shreyans",6 "password": "123",7 "role": "USER",8 "permissions": ["ORDER_READ"]9}1POST /api/user2Content-Type: application/json3
4{5 "username": "auser",6 "password": "123",7 "role": "USER",8 "permissions": ["ORDER_READ", "SALES_READ"]9}Test Authorization
1# Test 1: shreyans accessing orders — should PASS2GET /api/orders3Authorization: Basic c2hyZXlhbnM6MTIz (shreyans:123 encoded)4# Response: 200 "All orders have been fetched successfully."5
6# Test 2: shreyans accessing sales — should FAIL7GET /api/sales8Authorization: Basic c2hyZXlhbnM6MTIz9# Response: 403 Forbidden (no SALES_READ permission)10
11# Test 3: auser accessing sales — should PASS12GET /api/sales13Authorization: Basic YXVzZXI6MTIz (auser:123 encoded)14# Response: 200 "All sales have been fetched successfully."14. Common Mistakes
Mistake 1: Forgetting @EnableMethodSecurity
1// ❌ WRONG — @PreAuthorize is silently ignored2@Configuration3@EnableWebSecurity4public class SecurityConfig { ... }5
6// ✅ CORRECT7@Configuration8@EnableWebSecurity9@EnableMethodSecurity(prePostEnabled = true)10public class SecurityConfig { ... }Why it happens: The annotations compile and run without errors — they just have no effect. This is a subtle bug that can lead to security holes in production.
Mistake 2: Wrong Prefix in hasRole()
1// ❌ WRONG — hasRole already adds ROLE_ prefix internally2@PreAuthorize("hasRole('ROLE_USER')")3// This checks for "ROLE_ROLE_USER" in the authorities list → always false4
5// ✅ CORRECT6@PreAuthorize("hasRole('USER')")7// This checks for "ROLE_USER" in the authorities listMistake 3: Storing Roles Without ROLE_ Prefix in getAuthorities()
1// ❌ WRONG — stored without prefix2authorities.add(new SimpleGrantedAuthority(user.getRole()));3// Stores "USER" — but hasRole('USER') checks for "ROLE_USER" → mismatch4
5// ✅ CORRECT — stored with prefix6authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));7// Stores "ROLE_USER" — hasRole('USER') checks for "ROLE_USER" → matchMistake 4: Using @PostAuthorize for Mutating Operations
1// ❌ DANGEROUS — side effects happen before authorization check2@PostMapping("/orders")3@PostAuthorize("returnObject.userId == authentication.principal.id")4public OrderDTO createOrder(@RequestBody OrderRequest request) {5 // This saves to DB even if the user is unauthorized!6 return orderService.save(request);7}8
9// ✅ CORRECT — use @PreAuthorize for mutations10@PostMapping("/orders")11@PreAuthorize("#request.userId == authentication.principal.id")12public OrderDTO createOrder(@RequestBody OrderRequest request) {13 return orderService.save(request);14}Mistake 5: Putting Sensitive Logic in Both Layers Without Understanding Priority
1// If @PreAuthorize fails, @PostAuthorize is never reached2// If @PreAuthorize passes but @PostAuthorize fails, the method HAS already run3
4// This means: @PostAuthorize cannot undo side effects from the method body15. Best Practices
| Practice | Explanation |
|---|---|
Use @PreAuthorize for most cases | Checks before method execution — more efficient, no side effects |
Reserve @PostAuthorize for read-only, data-dependent checks | Only use when you need the return value for the authorization decision |
| Combine role + permission checks | hasRole('USER') and hasAuthority('ORDER_READ') — role for coarse, authority for fine-grained |
Use #param for path variable/body checks in PreAuthorize | More efficient than PostAuthorize when the decision can be made from input alone |
| Never put passwords or secrets in JWT payload/Claims | Even if using JWE for OAuth — minimize sensitive data in tokens |
| Explicit is better | Annotate every controller method, even if just @PreAuthorize("isAuthenticated()") — makes security intent clear |
Use @EnableMethodSecurity instead of deprecated @EnableGlobalMethodSecurity | Updated annotation for Spring Boot 3.x / Spring Security 6.x |
| Test both passing and failing cases | Security tests should verify 403 responses as much as 200 responses |
| Custom UserDetails for richer SpEL expressions | Add id, email, etc. to your UserDetails implementation to use them in SpEL |
| Apply method security at the service layer too | Annotate @Service methods for defense-in-depth when controllers and services can both be entry points |
16. Interview Notes
Common Interview Questions
Basics
| Question | Key Points |
|---|---|
| What is the difference between authentication and authorization in Spring Security? | Authentication = who you are (identity). Authorization = what you can do (permission). Spring Security handles both. |
| What are the two levels of authorization in Spring Security? | Security Filter Chain (URL-level) and Method-level (@PreAuthorize/@PostAuthorize) |
| Why would you prefer annotation-based authorization over filter-chain authorization? | Scalability — co-located with endpoint, avoids giant security config file, supports return-value checks |
| What annotation must be added to the config class to enable @PreAuthorize? | @EnableMethodSecurity(prePostEnabled = true) |
@PreAuthorize vs @PostAuthorize
| Question | Key Points |
|---|---|
| What is the difference between @PreAuthorize and @PostAuthorize? | Pre: authorization check BEFORE method executes. Post: check AFTER method executes, using returnObject |
| When would you use @PostAuthorize? | When the authorization decision depends on data returned by the method (e.g., verify returned record belongs to the caller) |
| Can you have both @PreAuthorize and @PostAuthorize on the same method? | Yes. PreAuthorize runs first. If it passes, method executes. Then PostAuthorize checks returnObject. |
What is returnObject in @PostAuthorize? | Special SpEL keyword that holds the method's return value. Spring Security auto-casts it to the method's return type. |
hasRole vs hasAuthority
| Question | Key Points |
|---|---|
| What is the difference between hasRole() and hasAuthority()? | Both call the same underlying code. hasRole() prepends ROLE_ prefix automatically. hasAuthority() checks as-is. |
| If I call hasRole('USER'), what does Spring actually check for in the authorities list? | ROLE_USER |
| Why shouldn't I write hasRole('ROLE_USER')? | hasRole already adds ROLE_ prefix. hasRole('ROLE_USER') would check for ROLE_ROLE_USER — always false. |
Internals
| Question | Key Points |
|---|---|
| How does @PreAuthorize actually get invoked before the method? | AOP interceptor: AuthorizationManagerBeforeMethodInterceptor intercepts the method call |
| What language is used inside @PreAuthorize strings? | Spring Expression Language (SpEL) |
| How does Spring parse the expression string inside @PreAuthorize? | SpEL parser converts it to an Abstract Syntax Tree (AST), then recursively evaluates each node |
| How can you check a method parameter in @PreAuthorize? | Using #paramName syntax: @PreAuthorize("#id == authentication.principal.id") |
| How does the interceptor know the current user's identity? | It reads the Authentication object from SecurityContextHolder.getContext().getAuthentication() |
Tricky/Advanced
| Question | Key Points |
|---|---|
| What happens if @EnableMethodSecurity is missing? | @PreAuthorize and @PostAuthorize are silently ignored — no error, but no security either |
| Can you use @PreAuthorize on a private method? | No. Spring AOP uses JDK dynamic proxies or CGLIB, which only intercept public methods on Spring beans |
| If @PostAuthorize fails, do the DB writes from the method body still persist? | Yes. The method runs fully. PostAuthorize only blocks the response, not the execution. This is why PostAuthorize should only be used for read operations. |
17. Summary
Quick Revision Bullets
- Two authorization levels: Filter-chain (URL-level) and Annotation-based (method-level). For large apps, annotation-based scales better.
- @EnableMethodSecurity(prePostEnabled = true) must be on your
@Configurationclass — without this, the annotations do nothing. - @PreAuthorize — authorization check before method executes. Method never runs if check fails.
- @PostAuthorize — authorization check after method executes using
returnObject. Method always runs; only the response is blocked. - hasRole('USER') → checks for
ROLE_USERin authorities list (prefix added automatically) - hasAuthority('ORDER_READ') → checks for
ORDER_READin authorities list (no prefix) - Both hasRole and hasAuthority call the same underlying
hasAnyAuthorityNamemethod. Difference is only the prefix. - Granted authorities = single flat list containing both roles and permissions. Populated in
getAuthorities()ofUserDetailsService. - SpEL keywords:
authentication,principal,returnObject,#paramName,hasRole(),hasAuthority(),and,or,not - Interceptors:
AuthorizationManagerBeforeMethodInterceptor(for Pre),AuthorizationManagerAfterMethodInterceptor(for Post) - AST: SpEL expression is parsed into an Abstract Syntax Tree and recursively evaluated
- Row-level security:
@PreAuthorize("#id == authentication.principal.id")prevents users from accessing other users' data - @PostAuthorize with returnObject:
returnObject.userId == authentication.principal.id— verifies returned data belongs to caller - Never use @PostAuthorize for mutating operations — side effects (DB writes) happen before the authorization check
18. Practice Questions
Easy
- What annotation must be added to the Spring Security configuration class to enable
@PreAuthorize? - What is the difference between
@PreAuthorizeand@PostAuthorize? - Write a
@PreAuthorizeexpression that allows only users with the roleADMIN. - What does
returnObjectrefer to inside@PostAuthorize? - What is the automatic prefix added by
hasRole()and what does that mean for how you store roles? - Name the two AOP interceptor classes used for
@PreAuthorizeand@PostAuthorize. - How do you reference a method parameter in a
@PreAuthorizeexpression?
Medium
- Explain why a user with
ROLE_USERstored in their authorities list would fail ahasRole('ROLE_USER')check. What is the correct fix? - Write an entity model and
UserDetailsServiceimplementation that supports both role-level and permission-level authorization. - A
GET /api/ordersendpoint should be accessible to any user who has the roleUSERAND either the permissionORDER_READorORDER_MANAGE. Write the@PreAuthorizeexpression. - A user with id=5 calls
GET /api/user/3. Using@PreAuthorizewith a path variable, write the annotation that blocks this request. - Explain the internal flow from a
@PreAuthorizeannotation being present on a method to the finaltrue/falseauthorization decision. Mention: interceptor, SpEL, AST, SecurityContextHolder. - What is the difference between filter-chain authorization and annotation-based authorization? When would you use each?
Hard
- A
GET /api/order/latestendpoint is annotated with both@PreAuthorizeand@PostAuthorize.@PreAuthorizepasses. The method executes and sends an email notification. Then@PostAuthorizefails. What happens? How should you redesign this? - Trace exactly what happens in the Spring Security internals (interceptor → SpEL parser → AST → method invocation) when the expression
"hasRole('USER') and (hasAuthority('ORDER_READ') or hasAuthority('ORDER_MANAGE'))"is evaluated. - You need to implement row-level security: each user should only be able to update their own profile. The user ID is in the request body (not a path variable). Write the controller method, DTO, and
@PreAuthorizeannotation. - An intern suggests: "Since
hasRole()andhasAuthority()call the same code, let's just usehasAuthority('ROLE_USER')everywhere to avoid confusion." Evaluate this proposal — what are the pros, cons, and risks? - Design the complete authorization strategy (entities,
getAuthorities(),SecurityConfig, controller annotations) for an e-commerce platform with rolesCUSTOMER,SELLER,ADMINand granular permissionsPRODUCT_READ,PRODUCT_CREATE,ORDER_READ,ORDER_CANCEL,USER_MANAGE.
@EnableMethodSecurity.Mastery check
How well can you recall this?
Finished this lesson?