In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the design patterns in the Spring Security framework". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the design patterns in the Spring Security framework"?
1. Template method mode
Template Pattern (template method pattern) is an abstract class that exposes a template that defines the method that executes it. Its subclasses can override the method implementation as needed, but the invocation will be made in the way defined in the abstract class, which is a behavioral pattern.
The advantages of the template method are as follows:
The common part of the code is extracted from the parent class to facilitate code reuse and extension. Some of the methods are implemented by subclasses, and subclasses can add corresponding functions by extension, which is in line with the principle of opening and closing. The disadvantages are as follows:
A subclass needs to be defined for each different implementation, resulting in an increase in the number of classes, a more complex system, and a more abstract design. The abstract method in the parent class is implemented by the subclass, and the result of the execution of the subclass will affect the result of the parent class and increase the difficulty of code understanding. After introducing the template method pattern, you may have guessed where the template method pattern is used in Spring Security.
Let me give you a few simple examples.
The first example is the design of the AbstractUserDetailsAuthenticationProvider class. Everyone knows that this class is used for validation, and the authentication logic is defined in this method, but this class defines two abstract methods:
RetrieveUser this method allows the user to get the user object from the data source. AdditionalAuthenticationChecks this method is used to do additional verification (verification of login credentials) these two abstract methods are implemented in DaoAuthenticationProvider. The implementation of DaoAuthenticationProvider is to load users from the database, and the default verification login credentials are all authentication passwords.
If your data source comes from somewhere else, or your login credentials are not passwords, then the custom class inherits from AbstractUserDetailsAuthenticationProvider and overrides the two methods in it.
two。 Responsibility chain model
Chain of Responsibility Pattern (chain of responsibility pattern), in which each recipient usually contains a reference to another, and if one object cannot process the request, it passes the same request to the next, and so on. In this process, the customer only needs to send the request to the responsibility chain, without paying attention to the processing details of the request and the delivery process of the request, so the responsibility chain decouples the sender of the request from the processor of the request.
The advantages of the chain of responsibility model are as follows:
Reduce the coupling between objects. The expansibility of the system is enhanced. When the workflow changes, you can dynamically change the members of the chain or transfer their order. Simplifies the connection between objects, so that each object only needs to maintain a reference to its successor, not all other handlers. Responsibility sharing, each class only needs to deal with its own work, in line with the principle of single responsibility of the class. The disadvantages are as follows:
Compared with the longer chain of responsibilities, the processing of requests may involve multiple processing objects, and the performance of the system will be affected to a certain extent. The rationality of the establishment of the responsibility chain depends on the client, which increases the complexity of the client. Obviously, the filter chain in Spring Security is a chain of responsibility model. After a request arrives, it is processed one by one by the filters in the filter chain. Each filter in the filter chain has different functions and does not interfere with each other. We can also dynamically configure the filters in the filter chain through HttpSecurity (that is, adding / removing filters in the filter chain).
The specific code in FilterChainProxy$VirtualFilterChain is as follows:
So let's take a look at VirtualFilterChain:
Private static class VirtualFilterChain implements FilterChain {private final FilterChain originalChain;private final List additionalFilters;private final FirewalledRequest firewalledRequest;private final int size;private int currentPosition = 0private VirtualFilterChain (FirewalledRequest firewalledRequest,FilterChain chain, List additionalFilters) {this.originalChain = chain;this.additionalFilters = additionalFilters;this.size = additionalFilters.size (); this.firewalledRequest = firewalledRequest;} @ Overridepublic void doFilter (ServletRequest request, ServletResponse response) throws IOException, ServletException {if (currentPosition = = size) {if (logger.isDebugEnabled ()) {logger.debug (UrlUtils.buildRequestUrl (firewalledRequest) + "reached end of additional filter chain) Proceeding with original chain ");} / / Deactivate path stripping as we exit the security filter chainthis.firewalledRequest.reset (); originalChain.doFilter (request, response);} else {currentPosition++;Filter nextFilter = additionalFilters.get (currentPosition-1); if (logger.isDebugEnabled ()) {logger.debug (UrlUtils.buildRequestUrl (firewalledRequest) +" at position "+ currentPosition+" of "+ size+" in additional filter chain; firing Filter:'"+ nextFilter.getClass (). GetSimpleName () +");} nextFilter.doFilter (request, response, this) The VirtualFilterChain class first declares five global properties, and originalChain represents the native filter chain, that is, Web Filter AdditionalFilters represents the filter chain in Spring Security; firewalledRequest represents the current request; size represents the number of filters in the filter chain; and currentPosition is the subscript when the filter chain is traversed. The doFilter method is the process in which the filter is executed one by one in Spring Security. If currentPosition = = size, the filter chain has been executed. At this time, call originalChain.doFilter to enter the native filter chain method and exit the Spring Security filter chain. Otherwise, each filter in the Spring Security filter chain is taken from the additionalFilters and the doFilter method is called one by one. NextFilter.doFilter is the filter chain that goes down one by one. For an introduction to FilterChainProxy, see: [in-depth understanding of FilterChainProxy [source code]]
3. Strategy mode
Strategy Pattern (Policy Mode), which defines a series of algorithms, encapsulates each algorithm, and allows them to replace each other. Policy mode allows the algorithm to change independently of the customers who use it, also known as policy mode (Policy).
Advantages of the policy model:
The policy model provides perfect support for the "opening and closing principle". Users can choose specific strategies without modifying the original system, and they can also flexibly expand new strategies. The policy pattern provides a way to manage related policies. The policy pattern provides a way to replace inheritance relationships. You can avoid using multiple conditional transfer statements by using policy mode. Disadvantages of the policy model:
The client must know all the policy classes and decide which one to use. The policy pattern will result in a large number of policy classes (the number of objects can be reduced to some extent by using the shared meta pattern). There are also several places where policy patterns are used in Spring Security.
The first is the storage of user login information.
By defining the method for storing login user information in SecurityContextHolder, three different policies are defined:
Public class SecurityContextHolder {/ / ~ Static fields/initializers// =
Public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"
Public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"
Public static final String MODE_GLOBAL = "MODE_GLOBAL"
Public static final String SYSTEM_PROPERTY = "spring.security.strategy"
Private static String strategyName = System.getProperty (SYSTEM_PROPERTY)
Private static SecurityContextHolderStrategy strategy
} users can choose which strategy to use! For more information, please see: [in Spring Security, I just want to get user login information from child threads. What should I do?]
Another is session concurrency management.
In the AbstractAuthenticationProcessingFilter#doFilter method, you have the following code:
Public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {/ / omit sessionStrategy.onAuthentication (authResult, request, response); / / omit} this is a policy mode.
For Session concurrency management, please refer to:
[what is a session fixing attack? How to defend against session fixing attacks in Spring Boot?] [how does Spring Security handle session sharing in a clustered deployment?] Of course, there are many such examples, so I will not enumerate them one by one.
4. Agent mode
Proxy Pattern (proxy pattern): provides a proxy to an object, and the reference to the original object is controlled by the proxy object. It is an object structural pattern.
Advantages of the proxy model:
The coupling degree of the system is reduced to some extent. The proxy object can extend the function of the target object. The proxy object protects the target object. Disadvantages:
The addition of a proxy between the client and the real object may result in slower processing of the request. The complexity of the system is increased. The most important application of proxy mode in Spring Security is the process of connecting Spring Security filter chain to Web Filter, using the DelegatingFilterProxy provided by Spring, which is a typical proxy mode:
Public class DelegatingFilterProxy extends GenericFilterBean {@ Overridepublic void doFilter (ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
/ / Lazily initialize the delegate if necessary.
Filter delegateToUse = this.delegate
If (delegateToUse = = null) {
Synchronized (this.delegateMonitor) {
DelegateToUse = this.delegate
If (delegateToUse = = null) {
WebApplicationContext wac = findWebApplicationContext ()
If (wac = = null) {
Throw new IllegalStateException ("No WebApplicationContext found:" +
"no ContextLoaderListener or DispatcherServlet registered?")
}
DelegateToUse = initDelegate (wac)
}
This.delegate = delegateToUse
}
}
/ / Let the delegate perform the actual doFilter operation.
InvokeDelegate (delegateToUse, request, response, filterChain)
}
} of course, there are many other places also use the agency mode, I will not list one by one, welcome friends to leave a message to add.
5. Adapter mode
Adapter Pattern (Adapter Mode), the commonly used mobile phone charger is called the power adapter, and its function is to convert the 220V voltage into the 5V voltage available for the mobile phone. So the adapter pattern actually has a similar effect, converting one interface into another that the customer wants, and the adapter pattern allows classes with incompatible interfaces to work together. The adapter pattern is divided into class adapter pattern, object adapter pattern and interface adapter pattern.
Advantages of the adapter pattern:
Decoupling, by introducing an adapter class to reuse the existing adaptor class without modifying the original code. Increase the transparency and reusability of the class. It has good flexibility and expansibility. Disadvantages:
Because Java does not support multiple inheritance, it can only adapt to one adaptor class at a time, and the target abstract class can only be an abstract class, not a concrete class, so its use has some limitations. There are also a lot of adapter patterns in Spring Security, such as our most common WebSecurityConfigurerAdapter, which allows two previously unrelated WebSecurity and HttpSecurity to work together.
6. Builder model
Builder Pattern (Builder pattern) separates the construction of a complex object from its representation, so that the same construction process can create different objects. Users only need to specify the type and content of the complex object to build the object without knowing the internal construction details.
Advantages of the builder model:
Decouple the product itself from the product creation process, so that the same creation process can create different product objects, and the client does not need to know the internal details of the product. Each product corresponds to a builder. Users can create different products using different builders, and the builders themselves can easily modify or add. The creation process of the product can be controlled more finely. Disadvantages:
The created product needs to have some similarity, and if the difference is too large, it is not suitable for the builder model. The complexity of the product itself will increase the complexity of the builder. There is also a lot of use of the builder pattern in Spring Security, such as the typical AuthenticationManagerBuilder, where the object it wants to build is AuthenticationManager, and the corresponding construction method is build. In the general builder pattern, the builder class name ends with builder, while the build method is named build ().
7. Observer mode
Observer (Observer pattern) means that there is an one-to-many dependency between multiple objects. When the state of an object changes, all objects that depend on it are notified and updated automatically. Observer pattern, also known as publish-subscribe pattern and model-view pattern, is an object behavior pattern.
The advantages of the observer model:
It reduces the coupling relationship between the target and the observer, which is an abstract coupling relationship. Disadvantages:
The dependency between the target and the observer has not been completely removed, and circular references may occur. When there are many observers, the execution efficiency of the program is reduced. In the Spring framework, the Observer pattern is used to implement the event handling capabilities of ApplicationContext. Spring provides us with the ApplicationEvent class and ApplicationListener interface to enable event handling. Any Bean in the Spring application that implements the ApplicationListener interface will receive a message pushed by ApplicationEvent as the event publisher. In this case, the event publisher is the Subject and the Observer of the Bean that implements the ApplicationListener.
Specific to Spring Security, such as login success event release, session destruction event, and so on, can be regarded as observer mode.
For example, the AbstractAuthenticationProcessingFilter#successfulAuthentication method:
Protected void successfulAuthentication (HttpServletRequest request,HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {if (logger.isDebugEnabled ()) {logger.debug ("Authentication success. Updating SecurityContextHolder to contain: "+ authResult);} SecurityContextHolder.getContext (). SetAuthentication (authResult); rememberMeServices.loginSuccess (request, response, authResult); / / Fire eventif (this.eventPublisher! = null) {eventPublisher.publishEvent (new InteractiveAuthenticationSuccessEvent (authResult, this.getClass ());} successHandler.onAuthenticationSuccess (request, response, authResult);} there are many similar events, such as session destruction events (see [Spring Security automatically kicks off the previous login user, a configuration is done!] Well, I won't list them one by one here.
8. Decoration mode
Decorator (decorative mode) refers to the pattern that dynamically adds some additional functions to the object without changing the existing object structure.
Advantages of decoration mode:
The function of a class can be flexibly extended. Disadvantages:
Many subclasses have been added to make the program very complex. There are also many applications for decoration patterns in Spring Security. The most typical is that a request will constantly change and adjust its function as it passes through the filter chain, and many classes of the request are designed through the decoration pattern, such as:
HeaderWriterRequestFirewalledRequestStrictHttpFirewallSaveToSessionRequestWrapper... Wait, there are a lot of similar things, so I won't repeat them one by one.
Thank you for your reading, the above is the content of "what are the design patterns in the Spring Security framework". After the study of this article, I believe you have a deeper understanding of what the design patterns in the Spring Security framework have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.