Spring Security and the Chain of Responsibility Design Pattern
From parent article
Chain of Responsibility Design Pattern
The Chain of Responsibility design pattern is a behavioural pattern that allows the client to pass a request along a chain of potential handlers until one of the them handles the request.
In terms of terminology the following are analogous.
Advantages
Components:
Chain Setup
When the client sends a request to the chain, each handler in the chain has two options:
2. Pass the Request: The handler may also decide not to process the request itself and instead pass it directly to the next handler in the chain without invoking the handle method.
Below is an architectural diagram of the Chain of Responsibility, where the dotted lines indicate the possible paths that the request might follow.
Example of a request that got rejected By Handler 2.
Example of a request that got handled by all handlers and is resolved
领英推荐
Spring Security's architecture is built on top of the Spring Servlet Architecture .
Spring Servlet Architecture
When a client sends a request to our web application,
Filters in the chain can decide whether to
If a filter processes the request and encounters an exception, the request does not get passed to the next filter; instead, an error response is sent back to the client.
Spring Security Filter Chain
Spring Security integrates with the Spring Servlet Architecture by introducing a dedicated security filter chain alongside the existing servlet filter chain. This security filter chain is responsible for handling authentication, authorization, and other security checks before the request reaches the business logic of the application (i.e., the controller).
The advantage of this architecture is that it is highly composable and configurable. We can easily add, remove, modify, reorder security filters, and even swap out entire Security Filter Chainsas needed.
Choosing Security Filter Chain
The FilterChainProxy manages a list of Security Filter Chain instances. When an incoming request is received, the matches method in the SecurityFilterChain interface determines which Security Filter Chain instance should handle the request.
Adding Security Filter to the Chain
Let’s add the UsernamePasswordAuthenticationFilter filter after Security Filter 2 and before Security Filter N.
Removing Security Filter from the Chain
Lets remove Security Filter 2 from the Chain.