Method-level security places access rules directly on Java methods, using annotations. Spring wraps the bean in a proxy that checks the rule before (or after) the method runs. The rule is enforced whoever calls the method, so it protects the business logic itself. It is used for sensitive operations such as deposit, withdrawal and closing an account.
Features
- Security rules written as annotations on service methods
- Expression support (SpEL) for roles, the logged-in user and method arguments
- Checks before the method runs, or on the returned object after it runs
- Fine-grained control that URL rules cannot give
- Works together with URL-level security
AccessDeniedExceptionbecomes a 403 response- Turned on with
@EnableMethodSecurity
Method-Level Security Types
- @PreAuthorize (used here): The rule is checked before the method runs, for example
hasAnyRole('TELLER','MANAGER')on deposit and withdraw. - @PostAuthorize (used here): The rule is checked after the method runs, so it can inspect the returned object. A customer can read an account only if
returnObject.holderUsername == authentication.name. - @Secured (used here): A simple role check without expressions, such as
@Secured("ROLE_MANAGER"). It needssecuredEnabled = true. - @PreFilter / @PostFilter: These remove items from a collection argument or result according to a rule. They are not built in this example.
Hands-on Experiment: Building a Bank Transaction Management System with Method-Level Security
Aim: To build a Spring Boot application that protects sensitive banking service methods with security annotations.
Software/Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ/Eclipse/VS Code), Postman
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
- Project: Maven | Language: Java | Spring Boot: 3.3.x
- Group:
com.example| Artifact:bank-transactions| Packaging: Jar | Java: 17 - Dependencies: Spring Web, Spring Security, Spring Data JPA, Validation, MySQL Driver
Step 2: Project Structure
bank-transactions
├── pom.xml
└── src/main
├── java/com/example/bankportal
│ ├── BankApplication.java
│ ├── entity/BankUser.java
│ ├── entity/Account.java
│ ├── repository/BankUserRepository.java
│ ├── repository/AccountRepository.java
│ ├── service/BankUserService.java
│ ├── service/AccountService.java
│ ├── service/SecurityConfig.java
│ └── controller/AccountController.java
└── resources/application.properties
Step 3: Create files according to the project structure
package com.example.bankportal.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
@Entity
@Table(name = "account")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(nullable = false, unique = true)
private String accountNumber;
// username of the customer who owns the account
@NotBlank
@Column(nullable = false)
private String holderUsername;
@NotNull
@DecimalMin("0.00")
@Column(nullable = false, precision = 15, scale = 2)
private BigDecimal balance;
public Account() {
}
public Account(String accountNumber, String holderUsername, BigDecimal balance) {
this.accountNumber = accountNumber;
this.holderUsername = holderUsername;
this.balance = balance;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getAccountNumber() { return accountNumber; }
public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; }
public String getHolderUsername() { return holderUsername; }
public void setHolderUsername(String holderUsername) { this.holderUsername = holderUsername; }
public BigDecimal getBalance() { return balance; }
public void setBalance(BigDecimal balance) { this.balance = balance; }
}
package com.example.bankportal.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "bank_user")
public class BankUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String fullName;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
// CUSTOMER, TELLER or MANAGER
@Column(nullable = false)
private String role;
private boolean enabled = true;
public BankUser() {
}
public BankUser(String fullName, String username, String password, String role) {
this.fullName = fullName;
this.username = username;
this.password = password;
this.role = role;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getRole() { return role; }
public void setRole(String role) { this.role = role; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
}
package com.example.bankportal.repository;
import com.example.bankportal.entity.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface AccountRepository extends JpaRepository<Account, Long> {
Optional<Account> findByAccountNumber(String accountNumber);
boolean existsByAccountNumber(String accountNumber);
}
package com.example.bankportal.repository;
import com.example.bankportal.entity.BankUser;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface BankUserRepository extends JpaRepository<BankUser, Long> {
Optional<BankUser> findByUsername(String username);
boolean existsByUsername(String username);
}
package com.example.bankportal.service;
import com.example.bankportal.entity.Account;
import com.example.bankportal.repository.AccountRepository;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Security rules are placed on the service methods, so they apply
* no matter which controller (or other class) calls them.
*/
@Service
public class AccountService {
private final AccountRepository repository;
public AccountService(AccountRepository repository) {
this.repository = repository;
}
// Only a MANAGER can open an account
@PreAuthorize("hasRole('MANAGER')")
public Account openAccount(Account account) {
if (repository.existsByAccountNumber(account.getAccountNumber())) {
throw new IllegalArgumentException("Account already exists: " + account.getAccountNumber());
}
return repository.save(account);
}
// @Secured: simple role check, no expressions
@Secured("ROLE_MANAGER")
public List<Account> getAllAccounts() {
return repository.findAll();
}
// Checked AFTER the method runs: a customer may read only his own account,
// a TELLER or MANAGER may read any account
@PostAuthorize("returnObject.holderUsername == authentication.name or hasAnyRole('TELLER','MANAGER')")
public Account getAccount(String accountNumber) {
return find(accountNumber);
}
@PreAuthorize("hasAnyRole('TELLER','MANAGER')")
@Transactional
public Account deposit(String accountNumber, BigDecimal amount) {
checkAmount(amount);
Account account = find(accountNumber);
account.setBalance(account.getBalance().add(amount));
return repository.save(account);
}
@PreAuthorize("hasAnyRole('TELLER','MANAGER')")
@Transactional
public Account withdraw(String accountNumber, BigDecimal amount) {
checkAmount(amount);
Account account = find(accountNumber);
if (account.getBalance().compareTo(amount) < 0) {
throw new IllegalArgumentException("Insufficient balance");
}
account.setBalance(account.getBalance().subtract(amount));
return repository.save(account);
}
@PreAuthorize("hasRole('MANAGER')")
public void closeAccount(String accountNumber) {
repository.delete(find(accountNumber));
}
// No security annotation: used only at start-up to load demo data
public void createDefaultAccounts() {
if (!repository.existsByAccountNumber("ACC1001")) {
repository.save(new Account("ACC1001", "customer1", new BigDecimal("5000.00")));
}
if (!repository.existsByAccountNumber("ACC1002")) {
repository.save(new Account("ACC1002", "customer2", new BigDecimal("3000.00")));
}
}
private Account find(String accountNumber) {
return repository.findByAccountNumber(accountNumber)
.orElseThrow(() -> new NoSuchElementException("Account not found: " + accountNumber));
}
private void checkAmount(BigDecimal amount) {
if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("Amount must be greater than zero");
}
}
}
package com.example.bankportal.service;
import com.example.bankportal.entity.BankUser;
import com.example.bankportal.repository.BankUserRepository;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class BankUserService implements UserDetailsService {
private final BankUserRepository repository;
private final PasswordEncoder passwordEncoder;
public BankUserService(BankUserRepository repository, PasswordEncoder passwordEncoder) {
this.repository = repository;
this.passwordEncoder = passwordEncoder;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
BankUser user = repository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
return User.builder()
.username(user.getUsername())
.password(user.getPassword())
.roles(user.getRole())
.disabled(!user.isEnabled())
.build();
}
public void createDefaultUsers() {
seed("Customer One", "customer1", "cust123", "CUSTOMER");
seed("Customer Two", "customer2", "cust456", "CUSTOMER");
seed("Teller One", "teller1", "teller123", "TELLER");
seed("Manager One", "manager1", "manager123", "MANAGER");
}
private void seed(String fullName, String username, String password, String role) {
if (!repository.existsByUsername(username)) {
repository.save(new BankUser(fullName, username, passwordEncoder.encode(password), role));
}
}
}
package com.example.bankportal.service;
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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true) // @PreAuthorize and @PostAuthorize are on by default
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // REST API tested with Postman
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// URL level only requires a login; the role rules are on the service methods
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
package com.example.bankportal.controller;
import com.example.bankportal.entity.Account;
import com.example.bankportal.service.AccountService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
private final AccountService service;
public AccountController(AccountService service) {
this.service = service;
}
@PostMapping
public ResponseEntity<Account> open(@Valid @RequestBody Account account) {
return ResponseEntity.status(HttpStatus.CREATED).body(service.openAccount(account));
}
@GetMapping
public List<Account> getAll() {
return service.getAllAccounts();
}
@GetMapping("/{accountNumber}")
public Account get(@PathVariable String accountNumber) {
return service.getAccount(accountNumber);
}
@PostMapping("/{accountNumber}/deposit")
public Account deposit(@PathVariable String accountNumber, @RequestBody Map<String, BigDecimal> body) {
return service.deposit(accountNumber, body.get("amount"));
}
@PostMapping("/{accountNumber}/withdraw")
public Account withdraw(@PathVariable String accountNumber, @RequestBody Map<String, BigDecimal> body) {
return service.withdraw(accountNumber, body.get("amount"));
}
@DeleteMapping("/{accountNumber}")
public Map<String, String> close(@PathVariable String accountNumber) {
service.closeAccount(accountNumber);
return Map.of("message", "Account closed: " + accountNumber);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> badRequest(IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
@ExceptionHandler(NoSuchElementException.class)
public ResponseEntity<Map<String, String>> notFound(NoSuchElementException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", ex.getMessage()));
}
}
package com.example.bankportal;
import com.example.bankportal.service.AccountService;
import com.example.bankportal.service.BankUserService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class BankApplication {
public static void main(String[] args) {
SpringApplication.run(BankApplication.class, args);
}
// Creates demo users and accounts on first start
@Bean
CommandLineRunner seedData(BankUserService userService, AccountService accountService) {
return args -> {
userService.createDefaultUsers();
accountService.createDefaultAccounts();
};
}
}
spring.application.name=bank-transactions
server.port=8080
# MySQL (database is created automatically if missing)
spring.datasource.url=jdbc:mysql://localhost:3306/bank_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Code language: PHP (php)
Step 4: Run the BankApplication


