Spring Security protects an application with a SecurityFilterChain, which is an ordered list of servlet filters. Every request passes through these filters one by one before it reaches a controller. Custom filters let you add your own checks, such as logging, rate limiting or API key validation. It is used so that bad or unauthorized requests are stopped early, before any shopping service runs.
Features
- One ordered chain of filters for all requests
- Custom filters written by extending
OncePerRequestFilter - Exact filter position control (
addFilterBefore,addFilterAfter) - A filter can stop a request and write its own response (401, 429)
- Built-in filters (Basic authentication, exception handling, authorization) work in the same chain
- URL rules by HTTP method and role
- Filter order visible in the console through
FilterChainProxylogging
SecurityFilterChain and Custom Filter Types
- Built-in filters: Spring Security adds filters such as
BasicAuthenticationFilter,ExceptionTranslationFilterandAuthorizationFilterfor you. They run in a fixed order. - Custom filters (used here): A class extending
OncePerRequestFilterruns once per request. This example has three:RequestLoggingFilter,RateLimitFilterandApiKeyFilter. - Filter placement:
addFilterBefore,addFilterAfterandaddFilterAtdecide where a custom filter runs. Here the three filters run in the order logging, rate limit, API key, all beforeBasicAuthenticationFilter. - Multiple SecurityFilterChain beans: Different URL patterns can have different chains using
securityMatcherand@Order, for example one chain for/api/**and another for/admin/**. This is not built in this example.
Hands-on Experiment: Building an Online Shopping Security System with Custom Security Filters
Aim: To build a Spring Boot application where custom filters log, rate-limit and validate every request before the shopping services are reached.
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:shop-security| Packaging: Jar | Java: 17 - Dependencies: Spring Web, Spring Security, Spring Data JPA, Validation, MySQL Driver
Step 2: Project Structure
shop-security
├── pom.xml
└── src/main
├── java/com/example/shopsecurity
│ ├── ShopSecurityApplication.java
│ ├── entity/ShopUser.java, Product.java, ShopOrder.java
│ ├── repository/ShopUserRepository.java, ProductRepository.java, ShopOrderRepository.java
│ ├── service/ShopUserService.java
│ ├── service/ShopService.java
│ ├── service/RequestLoggingFilter.java
│ ├── service/RateLimitFilter.java
│ ├── service/ApiKeyFilter.java
│ ├── service/SecurityConfig.java
│ ├── controller/ProductController.java
│ └── controller/OrderController.java
└── resources/application.properties
Step 3: Create the files according to the project structure
package com.example.shopsecurity.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.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(nullable = false)
private String name;
@NotNull
@DecimalMin("0.01")
@Column(nullable = false, precision = 12, scale = 2)
private BigDecimal price;
@Min(0)
private int stock;
public Product() {
}
public Product(String name, BigDecimal price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public int getStock() { return stock; }
public void setStock(int stock) { this.stock = stock; }
}
package com.example.shopsecurity.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 java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Table(name = "shop_order")
public class ShopOrder {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String customerUsername;
@Column(nullable = false)
private String productName;
private int quantity;
@Column(precision = 14, scale = 2)
private BigDecimal totalAmount;
private LocalDateTime orderedAt;
public ShopOrder() {
}
public ShopOrder(String customerUsername, String productName, int quantity, BigDecimal totalAmount) {
this.customerUsername = customerUsername;
this.productName = productName;
this.quantity = quantity;
this.totalAmount = totalAmount;
this.orderedAt = LocalDateTime.now();
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getCustomerUsername() { return customerUsername; }
public void setCustomerUsername(String customerUsername) { this.customerUsername = customerUsername; }
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; }
public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public BigDecimal getTotalAmount() { return totalAmount; }
public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
public LocalDateTime getOrderedAt() { return orderedAt; }
public void setOrderedAt(LocalDateTime orderedAt) { this.orderedAt = orderedAt; }
}
package com.example.shopsecurity.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 = "shop_user")
public class ShopUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
// CUSTOMER or ADMIN
@Column(nullable = false)
private String role;
public ShopUser() {
}
public ShopUser(String username, String password, String role) {
this.username = username;
this.password = password;
this.role = role;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
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; }
}
package com.example.shopsecurity.repository;
import com.example.shopsecurity.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
package com.example.shopsecurity.repository;
import com.example.shopsecurity.entity.ShopOrder;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ShopOrderRepository extends JpaRepository<ShopOrder, Long> {
List<ShopOrder> findByCustomerUsername(String customerUsername);
}
package com.example.shopsecurity.repository;
import com.example.shopsecurity.entity.ShopUser;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface ShopUserRepository extends JpaRepository<ShopUser, Long> {
Optional<ShopUser> findByUsername(String username);
boolean existsByUsername(String username);
}
package com.example.shopsecurity.service;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
/**
* Filter 3: every request must carry the shop's API key in the X-API-KEY header.
* A request without a valid key is stopped here, before login is even checked.
*/
public class ApiKeyFilter extends OncePerRequestFilter {
private final String validApiKey;
public ApiKeyFilter(String validApiKey) {
this.validApiKey = validApiKey;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String apiKey = request.getHeader("X-API-KEY");
boolean valid = apiKey != null && MessageDigest.isEqual(
apiKey.getBytes(StandardCharsets.UTF_8), validApiKey.getBytes(StandardCharsets.UTF_8));
if (!valid) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.getWriter().write("{\"error\":\"Invalid or missing API key\"}");
return; // chain stops here
}
chain.doFilter(request, response);
}
}
package com.example.shopsecurity.service;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Filter 2: allows only a limited number of requests per client IP in a time window.
* Too many requests -> 429 before any login check happens.
*/
public class RateLimitFilter extends OncePerRequestFilter {
private static class Window {
long start;
int count;
Window(long start) {
this.start = start;
}
}
private final int maxRequests;
private final long windowMillis;
private final Map<String, Window> windows = new ConcurrentHashMap<>();
public RateLimitFilter(int maxRequests, int windowSeconds) {
this.maxRequests = maxRequests;
this.windowMillis = windowSeconds * 1000L;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
long now = System.currentTimeMillis();
Window window = windows.computeIfAbsent(request.getRemoteAddr(), ip -> new Window(now));
boolean allowed;
synchronized (window) {
if (now - window.start > windowMillis) {
window.start = now;
window.count = 0;
}
window.count++;
allowed = window.count <= maxRequests;
}
if (!allowed) {
response.setStatus(429);
response.setContentType("application/json");
response.getWriter().write("{\"error\":\"Too many requests. Try again later\"}");
return; // chain stops here
}
chain.doFilter(request, response);
}
}
package com.example.shopsecurity.service;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* Filter 1: logs every request and the final response status.
* It is NOT a Spring bean; SecurityConfig adds it to the security chain,
* so it runs only once, inside the chain.
*/
public class RequestLoggingFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(RequestLoggingFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
long start = System.currentTimeMillis();
try {
chain.doFilter(request, response);
} finally {
log.info("REQUEST {} {} -> {} ({} ms)", request.getMethod(), request.getRequestURI(),
response.getStatus(), System.currentTimeMillis() - start);
}
}
}
package com.example.shopsecurity.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
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;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http,
@Value("${app.api-key}") String apiKey,
@Value("${app.rate-limit.max-requests}") int maxRequests,
@Value("${app.rate-limit.window-seconds}") int windowSeconds) throws Exception {
RequestLoggingFilter loggingFilter = new RequestLoggingFilter();
RateLimitFilter rateLimitFilter = new RateLimitFilter(maxRequests, windowSeconds);
ApiKeyFilter apiKeyFilter = new ApiKeyFilter(apiKey);
http
.csrf(csrf -> csrf.disable()) // REST API tested with Postman
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// Custom filters. Order of execution:
// RequestLoggingFilter -> RateLimitFilter -> ApiKeyFilter -> BasicAuthenticationFilter
.addFilterBefore(loggingFilter, BasicAuthenticationFilter.class)
.addFilterAfter(rateLimitFilter, RequestLoggingFilter.class)
.addFilterAfter(apiKeyFilter, RateLimitFilter.class)
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/products", "/api/products/**").permitAll()
.requestMatchers(HttpMethod.POST, "/api/products").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/api/orders").hasRole("CUSTOMER")
.requestMatchers(HttpMethod.GET, "/api/orders/my").hasRole("CUSTOMER")
.requestMatchers(HttpMethod.GET, "/api/orders").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
package com.example.shopsecurity.service;
import com.example.shopsecurity.entity.Product;
import com.example.shopsecurity.entity.ShopOrder;
import com.example.shopsecurity.repository.ProductRepository;
import com.example.shopsecurity.repository.ShopOrderRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.NoSuchElementException;
@Service
public class ShopService {
private final ProductRepository productRepository;
private final ShopOrderRepository orderRepository;
public ShopService(ProductRepository productRepository, ShopOrderRepository orderRepository) {
this.productRepository = productRepository;
this.orderRepository = orderRepository;
}
public List<Product> getProducts() {
return productRepository.findAll();
}
public Product getProduct(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new NoSuchElementException("Product not found: " + id));
}
public Product addProduct(Product product) {
return productRepository.save(product);
}
@Transactional
public ShopOrder placeOrder(String username, Integer productId, Integer quantity) {
if (productId == null || quantity == null || quantity <= 0) {
throw new IllegalArgumentException("productId and a quantity greater than zero are required");
}
Product product = getProduct(productId.longValue());
if (product.getStock() < quantity) {
throw new IllegalArgumentException("Only " + product.getStock() + " item(s) in stock");
}
product.setStock(product.getStock() - quantity);
productRepository.save(product);
BigDecimal total = product.getPrice().multiply(BigDecimal.valueOf(quantity));
return orderRepository.save(new ShopOrder(username, product.getName(), quantity, total));
}
public List<ShopOrder> getOrdersOf(String username) {
return orderRepository.findByCustomerUsername(username);
}
public List<ShopOrder> getAllOrders() {
return orderRepository.findAll();
}
public void createDefaultProducts() {
if (productRepository.count() == 0) {
productRepository.save(new Product("Laptop", new BigDecimal("55000.00"), 10));
productRepository.save(new Product("Headphones", new BigDecimal("1999.00"), 50));
productRepository.save(new Product("Smartphone", new BigDecimal("25000.00"), 20));
}
}
}
package com.example.shopsecurity.service;
import com.example.shopsecurity.entity.ShopUser;
import com.example.shopsecurity.repository.ShopUserRepository;
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 ShopUserService implements UserDetailsService {
private final ShopUserRepository repository;
private final PasswordEncoder passwordEncoder;
public ShopUserService(ShopUserRepository repository, PasswordEncoder passwordEncoder) {
this.repository = repository;
this.passwordEncoder = passwordEncoder;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
ShopUser user = repository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
return User.builder()
.username(user.getUsername())
.password(user.getPassword())
.roles(user.getRole())
.build();
}
public void createDefaultUsers() {
seed("customer1", "cust123", "CUSTOMER");
seed("admin", "admin123", "ADMIN");
}
private void seed(String username, String password, String role) {
if (!repository.existsByUsername(username)) {
repository.save(new ShopUser(username, passwordEncoder.encode(password), role));
}
}
}
package com.example.shopsecurity.controller;
import com.example.shopsecurity.entity.ShopOrder;
import com.example.shopsecurity.service.ShopService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
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.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
@RestController
@RequestMapping("/api/orders")
public class OrderController {
private final ShopService service;
public OrderController(ShopService service) {
this.service = service;
}
@PostMapping
public ResponseEntity<ShopOrder> place(@RequestBody Map<String, Integer> body, Authentication authentication) {
ShopOrder order = service.placeOrder(authentication.getName(), body.get("productId"), body.get("quantity"));
return ResponseEntity.status(HttpStatus.CREATED).body(order);
}
@GetMapping("/my")
public List<ShopOrder> myOrders(Authentication authentication) {
return service.getOrdersOf(authentication.getName());
}
@GetMapping
public List<ShopOrder> allOrders() {
return service.getAllOrders();
}
@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.shopsecurity.controller;
import com.example.shopsecurity.entity.Product;
import com.example.shopsecurity.service.ShopService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ShopService service;
public ProductController(ShopService service) {
this.service = service;
}
@GetMapping
public List<Product> getAll() {
return service.getProducts();
}
@GetMapping("/{id}")
public Product getOne(@PathVariable Long id) {
return service.getProduct(id);
}
@PostMapping
public ResponseEntity<Product> add(@Valid @RequestBody Product product) {
return ResponseEntity.status(HttpStatus.CREATED).body(service.addProduct(product));
}
@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.shopsecurity;
import com.example.shopsecurity.service.ShopService;
import com.example.shopsecurity.service.ShopUserService;
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 ShopSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(ShopSecurityApplication.class, args);
}
// Creates demo users and products on first start
@Bean
CommandLineRunner seedData(ShopUserService userService, ShopService shopService) {
return args -> {
userService.createDefaultUsers();
shopService.createDefaultProducts();
};
}
}
spring.application.name=shop-security
server.port=8080
# MySQL (database is created automatically if missing)
spring.datasource.url=jdbc:mysql://localhost:3306/shop_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
# Settings used by the custom filters
app.api-key=SHOP-KEY-12345
app.rate-limit.max-requests=10
app.rate-limit.window-seconds=60
# Prints every filter of the chain for each request (shows the filter order)
logging.level.org.springframework.security.web.FilterChainProxy=TRACECode language: PHP (php)
Step 4: Run the ShopSecurityApplication
URLs and Payloads
Add the header X-API-KEY: SHOP-KEY-12345 to every request in Postman (Headers tab). For protected URLs also set Authorization → Basic Auth.
Logins: customer1 / cust123 (CUSTOMER) and admin / admin123 (ADMIN)


