Definition
- @PreAuthorize – evaluates a Spring Expression Language (SpEL) expression before the method runs; blocks the call with AccessDeniedException if the expression returns false.
- @PostAuthorize – evaluates after the method returns; can inspect the return value (via
returnObject) to decide whether to allow the result. - @PreFilter – filters elements of a collection parameter before the method executes; only matching elements are passed to the method.
- @PostFilter – filters elements of the return collection after the method executes; removes elements that do not match the expression.
- @EnableMethodSecurity – the modern annotation (Spring Security 6+) that activates method-level security; replaces the deprecated @EnableGlobalMethodSecurity.
In National Bank of India, URL-level security is like the main entrance guard who checks if you are a bank employee. Method-level security is like the vault room rules: even if you are inside the bank, only the vault manager (ROLE_VAULT_MANAGER) can open the vault. @PreAuthorize is the check before you turn the key. @PostAuthorize is the check after you retrieve a document from the vault: did you retrieve your own department's document or someone else's?
Understanding the Concepts
What is method-level security?
Method-level security applies authorization checks directly on individual methods in your Spring beans. It complements URL-level security (configured in SecurityFilterChain) by protecting business logic regardless of which controller or endpoint invokes it.
You enable it with:
package com.bank.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}
Note: @EnableMethodSecurity is the modern replacement for @EnableGlobalMethodSecurity. The old annotation required explicit flags like prePostEnabled = true. The new one enables @PreAuthorize and @PostAuthorize by default.
How does @PreAuthorize work?
@PreAuthorize evaluates a SpEL expression before the method executes. If the expression returns false, Spring throws AccessDeniedException and the method never runs.
package com.bank.service;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class AccountService {
// Only users with ROLE_ADMIN can close accounts
@PreAuthorize("hasRole('ADMIN')")
public void closeAccount(String accountNumber) {
// Close account logic
}
// Only users with TRANSFER_APPROVE authority can approve transfers
@PreAuthorize("hasAuthority('TRANSFER_APPROVE')")
public void approveTransfer(Long transferId) {
// Approve transfer logic
}
// Only the account owner can view their own balance
@PreAuthorize("#accountHolder == authentication.name")
public BigDecimal getBalance(String accountHolder) {
// Fetch balance from database
return BigDecimal.valueOf(50000.00);
}
// Require both role AND specific authority
@PreAuthorize("hasRole('MANAGER') and hasAuthority('LOAN_APPROVE')")
public void approveLoan(Long loanId, BigDecimal amount) {
// Approve loan logic
}
}
- The SpEL expression can use:
hasRole('ADMIN')– checks for ROLE_ADMIN authority.hasAuthority('TRANSFER_APPROVE')– checks for exact authority.authentication.name– the current user's username.#paramName– references a method parameter by name.and,or,not– logical operators.
How does @PostAuthorize work?
@PostAuthorize evaluates after the method returns. You can inspect the return value using returnObject.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.stereotype.Service;
@Service
public class AccountLookupService {
private final AccountRepository accountRepository;
public AccountLookupService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
// After loading the account, verify the current user is the owner
@PostAuthorize("returnObject.ownerUsername == authentication.name")
public Account getAccount(String accountNumber) {
return accountRepository.findByAccountNumber(accountNumber)
.orElseThrow(() -> new RuntimeException("Account not found"));
}
}
If Rajesh (logged in as "rajesh") calls getAccount("SAV2001") and the account is owned by "priya", the method executes but Spring throws AccessDeniedException before returning the result to the caller.
Use @PostAuthorize cautiously: the method body still runs (including database queries and side effects) even if authorization fails afterward.
How do @PreFilter and @PostFilter work?
@PreFilter removes elements from a collection parameter before the method runs. @PostFilter removes elements from the return collection after the method runs.
package com.bank.service;
import com.bank.model.Transaction;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TransactionService {
// Only process transactions owned by the current user
@PreFilter("filterObject.ownerUsername == authentication.name")
public void processTransactions(List<Transaction> transactions) {
for (Transaction tx : transactions) {
// Only the user's own transactions reach here
}
}
// Return only transactions belonging to the current user
@PostFilter("filterObject.ownerUsername == authentication.name")
public List<Transaction> getAllTransactions() {
return transactionRepository.findAll();
}
}
@PostFilter loads all data from the database and then filters in memory. For large datasets, this is inefficient. Prefer adding a WHERE clause to the query instead.
What is the AOP proxy limitation?
Method security relies on Spring AOP proxies. When a method is called through the proxy, the security interceptor runs. But when a method calls another method in the same class (self-invocation), the proxy is bypassed.
@Service
public class LoanService {
// This method is secured
@PreAuthorize("hasRole('MANAGER')")
public void approveLoan(Long loanId) {
// Approve logic
}
// This method calls approveLoan internally
// The security check on approveLoan is BYPASSED
public void processLoanApplication(Long loanId) {
// ... validation logic ...
this.approveLoan(loanId); // Self-invocation: NO security check
}
}
The fix is to inject the bean into itself or move the secured method to a separate service:
// CORRECT: Separate service avoids self-invocation
@Service
public class LoanProcessingService {
private final LoanApprovalService approvalService;
public LoanProcessingService(LoanApprovalService approvalService) {
this.approvalService = approvalService;
}
public void processLoanApplication(Long loanId) {
// ... validation logic ...
approvalService.approveLoan(loanId); // Goes through proxy
}
}
@Service
public class LoanApprovalService {
@PreAuthorize("hasRole('MANAGER')")
public void approveLoan(Long loanId) {
// Approve logic
}
}
How do you use a custom authorization bean in SpEL?
For complex authorization logic, reference a Spring bean in the SpEL expression using @beanName:
package com.bank.security;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
@Component("accountAuth")
public class AccountAuthorization {
private final AccountRepository accountRepository;
public AccountAuthorization(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public boolean isOwner(Authentication auth, String accountNumber) {
return accountRepository.findByAccountNumber(accountNumber)
.map(account -> account.getOwnerUsername().equals(auth.getName()))
.orElse(false);
}
}
@PreAuthorize("@accountAuth.isOwner(authentication, #accountNumber)")
public AccountStatement getStatement(String accountNumber) {
// Only the account owner can view their statement
return statementService.generate(accountNumber);
}
This is cleaner than writing complex SpEL inline and is easier to unit test.
What are common mistakes?
1. Forgetting @EnableMethodSecurity:
// WRONG: @PreAuthorize is ignored without @EnableMethodSecurity
@Service
public class AccountService {
@PreAuthorize("hasRole('ADMIN')")
public void closeAccount(String accountNumber) { }
}
// No error, no warning: the method is accessible to everyone
// CORRECT: Enable method security
@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig { }
2. Using @Secured instead of @PreAuthorize:
// LESS FLEXIBLE: @Secured only supports role names, no SpEL
@Secured("ROLE_ADMIN")
public void closeAccount(String accountNumber) { }
// MORE FLEXIBLE: @PreAuthorize supports full SpEL expressions
@PreAuthorize("hasRole('ADMIN') and #amount.compareTo(T(java.math.BigDecimal).valueOf(100000)) < 0")
public void approveTransfer(BigDecimal amount) { }
When should you use method security vs URL security?
Use both together for defense in depth:
| Use case | URL security (SecurityFilterChain) | Method security (@PreAuthorize) |
|---|---|---|
| Broad endpoint access | Yes: /admin/** requires ADMIN role | Backup: @PreAuthorize on service methods |
| Resource ownership | Difficult: URLs do not encode ownership | Yes: #accountNumber == ... |
| Reusable business logic | No: only applies to HTTP requests | Yes: applies to any caller (controller, scheduler, event listener) |
| Performance | Cheaper: checks at filter level | Slightly more overhead: AOP proxy interception |
What should a senior engineer know?
- Method security annotations work on any Spring-managed bean, not just controllers. Secure service-layer methods so the rules apply even if the method is called from a scheduler or message listener.
- @PreAuthorize expressions are compiled to SpEL ASTs at application startup. Invalid expressions fail at startup, not at runtime.
- For reactive applications (WebFlux), use
@PreAuthorizewithReactiveMethodSecurityConfiguration. - Consider writing integration tests that verify method security using
@WithMockUserand@WithAnonymousUser.
Visual Overview
┌──────────────────────────────────────────────┐
│ HTTP Request: GET /api/accounts/SAV2001 │
└──────────────────────┬───────────────────────┘
│
▼
┌──────────────────────────────────────────────┐
│ SecurityFilterChain │
│ URL-level check: /api/accounts/** → authenticated │
└──────────────────────┬───────────────────────┘
│ PASS
▼
┌──────────────────────────────────────────────┐
│ AccountController.getAccount("SAV2001") │
│ calls accountService.getAccount("SAV2001") │
└──────────────────────┬───────────────────────┘
│
▼
┌──────────────────────────────────────────────┐
│ Spring AOP Proxy │
│ @PreAuthorize("@accountAuth.isOwner(...)") │
│ Expression evaluates to: true │
└──────────────────────┬───────────────────────┘
│ PASS
▼
┌──────────────────────────────────────────────┐
│ AccountService.getAccount() executes │
│ Returns Account { owner: "rajesh" } │
└──────────────────────┬───────────────────────┘
│
▼
┌──────────────────────────────────────────────┐
│ @PostAuthorize check (if present) │
│ returnObject.ownerUsername == "rajesh" → true │
└──────────────────────────────────────────────┘
Key Takeaway
Method-level security gives you authorization control at the individual method level, going beyond what URL patterns alone can enforce. While SecurityFilterChain protects endpoints based on URL patterns, @PreAuthorize and @PostAuthorize protect business logic based on the user's identity, roles, and even the data being accessed.
In a banking application, URL security ensures only authenticated users reach the accounts API. But method security goes further: @PreAuthorize checks that the logged-in user is the account owner before revealing the balance. @PostAuthorize verifies the return value belongs to the user. A custom authorization bean encapsulates complex ownership checks that are reusable across multiple service methods.
The critical limitation is the AOP proxy. Method security works through Spring's proxy mechanism, which means self-invocation within the same class bypasses security checks entirely. Rajesh must structure his services so that secured methods are always called through the proxy: either from a different bean or through an injected reference.
The combination of URL-level and method-level security provides defense in depth. If someone finds a way to bypass the URL filter (misconfigured matcher, new endpoint without rules), the method-level check still blocks unauthorized access. Neither layer alone is sufficient for a production banking application.
The one sentence to remember: @PreAuthorize checks permissions before the method runs using SpEL expressions, but it only works when the method is called through a Spring AOP proxy, not through self-invocation.
---