In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "how to configure SecurityConfigurer". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. SecurityConfigurer
SecurityConfigurer itself is an interface, let's take a look at:
Public interface SecurityConfigurer {
Void init (B builder) throws Exception
Void configure (B builder) throws Exception
}
As you can see, there are mainly two methods in SecurityConfigurer, init and configure.
Init is an initialization method. Configure is a configuration method. The definition of the method is only standardized here, and the specific implementation is in different implementation classes.
It is important to note that the parameter type of both methods is a generic B, which is a subclass of SecurityBuilder, which is used to build the filter chain about SecurityBuilder.
SecurityConfigurer has three implementation classes:
SecurityConfigurerAdapterGlobalAuthenticationConfigurerAdapterWebSecurityConfigurer
Let's look at it separately.
1.1 SecurityConfigurerAdapter
SecurityConfigurerAdapter implements the SecurityConfigurer interface, and most of the xxxConfigurer we use are subclasses of SecurityConfigurerAdapter.
SecurityConfigurerAdapter also extends several very useful methods based on SecurityConfigurer. Let's take a look at:
Public abstract class SecurityConfigurerAdapter
Implements SecurityConfigurer {
Private B securityBuilder
Private CompositeObjectPostProcessor objectPostProcessor = new CompositeObjectPostProcessor ()
Public void init (B builder) throws Exception {
}
Public void configure (B builder) throws Exception {
}
Public B and () {
Return getBuilder ()
}
Protected final B getBuilder () {
If (securityBuilder = = null) {
Throw new IllegalStateException ("securityBuilder cannot be null")
}
Return securityBuilder
}
@ SuppressWarnings ("unchecked")
Protected T postProcess (T object) {
Return (T) this.objectPostProcessor.postProcess (object)
}
Public void addObjectPostProcessor (ObjectPostProcessor objectPostProcessor) {
This.objectPostProcessor.addObjectPostProcessor (objectPostProcessor)
}
Public void setBuilder (B builder) {
This.securityBuilder = builder
}
Private static final class CompositeObjectPostProcessor implements
ObjectPostProcessor {
Private List oppClass = opp.getClass ()
Class oppType = GenericTypeResolver.resolveTypeArgument (oppClass
ObjectPostProcessor.class)
If (oppType = = null | | oppType.isAssignableFrom (object.getClass () {
Object = opp.postProcess (object)
}
}
Return object
}
Private boolean addObjectPostProcessor (
ObjectPostProcessor objectPostProcessor) {
Boolean result = this.postProcessors.add (objectPostProcessor)
PostProcessors.sort (AnnotationAwareOrderComparator.INSTANCE)
Return result
}
}
}
CompositeObjectPostProcessor begins by declaring an instance of CompositeObjectPostProcessor, CompositeObjectPostProcessor is an implementation of ObjectPostProcessor, and ObjectPostProcessor itself is a post-processor, which has two implementations, AutowireBeanFactoryObjectPostProcessor and CompositeObjectPostProcessor, by default. Among them, AutowireBeanFactoryObjectPostProcessor mainly uses AutowireCapableBeanFactory to manually register Bean, because in Spring Security, many objects are manually new, and these new objects have nothing to do with the container. AutowireCapableBeanFactory can be used to inject these manually new objects into the container, and the main function of AutowireBeanFactoryObjectPostProcessor is to accomplish this. CompositeObjectPostProcessor is a composite object processor, which maintains a List collection. In most cases, only one piece of data is stored in this List collection, that is, AutowireBeanFactoryObjectPostProcessor, which is used to complete the operation of object injection into the container. If the user manually calls the addObjectPostProcessor method, then there will be an extra piece of data maintained in the CompositeObjectPostProcessor collection. In the CompositeObjectPostProcessor#postProcess method, it will traverse all the ObjectPostProcessor in the collection. One by one calls its postProcess method to post-process the object. And method, the return value of this method is a securityBuilder,securityBuilder that is actually HttpSecurity. When we configure different filters in HttpSecurity, we can use the and method for chain configuration, because the and method is defined and the securityBuilder instance is returned.
This is the main function of SecurityConfigurerAdapter, and most of the subsequent xxxConfigurer is based on this class.
1.2 GlobalAuthenticationConfigurerAdapter
GlobalAuthenticationConfigurerAdapter knows from the name that it is something related to the global configuration. It implements the SecurityConfigurerAdapter interface itself, but does not specifically implement the method, but only materializes the generics:
@ Order
Public abstract class GlobalAuthenticationConfigurerAdapter implements
SecurityConfigurer {
Public void init (AuthenticationManagerBuilder auth) throws Exception {
}
Public void configure (AuthenticationManagerBuilder auth) throws Exception {
}
}
As you can see, generics in SecurityConfigurer are now clearly AuthenticationManager and AuthenticationManagerBuilder. So the implementation class of GlobalAuthenticationConfigurerAdapter is mainly related to configuring AuthenticationManager in the future. Of course, the default username and password is also configured by its implementation class.
The AuthenticationManager we use in Spring Security can actually be divided into two types, one is local, the other is global, which is mainly global configuration.
1.3 WebSecurityConfigurer
Another implementation class is WebSecurityConfigurer, which may be a stranger to some of our buddies. In fact, it is the parent interface of WebSecurityConfigurerAdapter that we use every day.
So the role of WebSecurityConfigurer is clear: users extend user-defined configurations.
SecurityConfigurer defaults to these three implementations, and considering that most filter configurations are extended through SecurityConfigurerAdapter, we'll expand through this line today.
2. SecurityConfigurerAdapter
The implementation of SecurityConfigurerAdapter can be divided into three main categories:
UserDetailsAwareConfigurerAbstractHttpConfigurerLdapAuthenticationProviderConfigurer
Considering that LDAP is rarely used now, let me focus on the first two.
2.1 UserDetailsAwareConfigurer
This configuration class probably knows from the name that it is used to configure the user class.
AbstractDaoAuthenticationConfigurer
What you do in AbstractDaoAuthenticationConfigurer is relatively simple, mainly by constructing a default DaoAuthenticationProvider and configuring it with PasswordEncoder and UserDetailsService.
UserDetailsServiceConfigurer
UserDetailsServiceConfigurer rewrites the configure method in AbstractDaoAuthenticationConfigurer, adding the initUserDetailsService method before the execution of the configure method to facilitate developers to initialize the UserDetailsService in its own way. However, the initUserDetailsService method here is null.
UserDetailsManagerConfigurer
UserDetailsManagerConfigurer implements the initUserDetailsService method defined in UserDetailsServiceConfigurer, and the specific implementation logic is to store the UserDetails built by UserDetailsBuilder and the users in the UserDetails prepared in advance into UserDetailsService.
This class also adds a withUser method to add users and a UserDetailsBuilder to build users. The logic is relatively simple, and friends can check it for themselves.
JdbcUserDetailsManagerConfigurer
JdbcUserDetailsManagerConfigurer complements the DataSource object on the basis of the parent class, and also provides the corresponding database query methods.
InMemoryUserDetailsManagerConfigurer
InMemoryUserDetailsManagerConfigurer overrides the constructor on top of the parent class, defining the UserDetailsService instance in the parent class as InMemoryUserDetailsManager.
DaoAuthenticationConfigurer
DaoAuthenticationConfigurer inherits from AbstractDaoAuthenticationConfigurer and just modifies userDetailsService in the constructor.
Some friends may want to ask, JdbcUserDetailsManagerConfigurer or InMemoryUserDetailsManagerConfigurer, where can I use it?
Brother Song, let me give you a simple example:
@ Configuration
Public class SecurityConfig extends WebSecurityConfigurerAdapter {
@ Override
Protected void configure (AuthenticationManagerBuilder auth) throws Exception {
Auth.inMemoryAuthentication () .withUser (javaboy)
.password ("{noop} 123")
.customers ("admin")
}
@ Override
Protected void configure (HttpSecurity http) throws Exception {
Http.authorizeRequests ()
.anyRequest () .authenticated ()
/ / omit
}
}
When you call auth.inMemoryAuthentication for configuration, you actually call InMemoryUserDetailsManagerConfigurer.
Now you get it!
2.2 AbstractHttpConfigurer
There are a lot of things in the AbstractHttpConfigurer school, and all of our filter configurations are subclasses of it. Let's take a look at what classes there are.
As you can see, there are still a lot of implementation classes.
Let's look at it one by one.
2.2.1 AbstractHttpConfigurer
AbstractHttpConfigurer inherits from SecurityConfigurerAdapter and adds two methods, disable and withObjectPostProcessor:
Public abstract class AbstractHttpConfigurer
Extends SecurityConfigurerAdapter {
/ * *
* Disables the {@ link AbstractHttpConfigurer} by removing it. After doing so a fresh
* version of the configuration can be applied.
*
* @ return the {@ link HttpSecurityBuilder} for additional customizations
, /
@ SuppressWarnings ("unchecked")
Public B disable () {
GetBuilder () .removeConfigurer (getClass ()
Return getBuilder ()
}
@ SuppressWarnings ("unchecked")
Public T withObjectPostProcessor (ObjectPostProcessor objectPostProcessor) {
AddObjectPostProcessor (objectPostProcessor)
Return (T) this
}
}
Brother Song has introduced these two methods to you before. Disable is basically everyone's old acquaintance, and our commonly used .csrf (). Disable () comes from here, so we can also see the implementation principle of disable, that is, removing the relevant xxxConfigurer,getBuilder method from getBuilder is actually HttpSecurity, so removing xxxConfigurer is actually removing a filter from the filter chain. For example, .csrf () .disable () removes the filter that handles csrf.
Another added method is withObjectPostProcessor, which adds a manually added post processor for the configuration class. In fact, a similar method in the parent class of AbstractHttpConfigurer is addObjectPostProcessor, but addObjectPostProcessor is just an add method, and the return value of withObjectPostProcessor is void, while the return value of withObjectPostProcessor is the current configuration class, that is, xxxConfigurer, so if you use withObjectPostProcessor, you can use chained configuration.
2.2.2 AbstractAuthenticationFilterConfigurer
The AbstractAuthenticationFilterConfigurer class has many functions, and the source code is quite long. But we only need to grasp two points, the init method and the configure method, because these two methods are the soul of all xxxConfigurer.
@ Override
Public void init (B http) throws Exception {
UpdateAuthenticationDefaults ()
UpdateAccessDefaults (http)
RegisterDefaultAuthenticationEntryPoint (http)
}
The init method does three main things:
UpdateAuthenticationDefaults is mainly configured with login processing address, failed jump address, logout successful jump address. The updateAccessDefaults method mainly sets the permitAll of loginPage, loginProcessingUrl, and failureUrl (if the user has configured permitAll). RegisterDefaultAuthenticationEntryPoint is the handler for registering exceptions.
Let's look at the configure method:
@ Override
Public void configure (B http) throws Exception {
PortMapper portMapper = http.getSharedObject (PortMapper.class)
If (portMapper! = null) {
AuthenticationEntryPoint.setPortMapper (portMapper)
}
RequestCache requestCache = http.getSharedObject (RequestCache.class)
If (requestCache! = null) {
This.defaultSuccessHandler.setRequestCache (requestCache)
}
AuthFilter.setAuthenticationManager (http
.getSharedObject (AuthenticationManager.class))
AuthFilter.setAuthenticationSuccessHandler (successHandler)
AuthFilter.setAuthenticationFailureHandler (failureHandler)
If (authenticationDetailsSource! = null) {
AuthFilter.setAuthenticationDetailsSource (authenticationDetailsSource)
}
SessionAuthenticationStrategy sessionAuthenticationStrategy = http
.getSharedObject (SessionAuthenticationStrategy.class)
If (sessionAuthenticationStrategy! = null) {
AuthFilter.setSessionAuthenticationStrategy (sessionAuthenticationStrategy)
}
RememberMeServices rememberMeServices = http
.getSharedObject (RememberMeServices.class)
If (rememberMeServices! = null) {
AuthFilter.setRememberMeServices (rememberMeServices)
}
F filter = postProcess (authFilter)
Http.addFilter (filter)
}
The logic in configure is simple. Build various callback functions and set them to authFilter,authFilter, then go to postProcess to register in the Spring container, and finally add authFilter to the filter chain.
This is the main function of AbstractAuthenticationFilterConfigurer. We need to remind you that what we configure on a daily basis, such as:
LoginPageloginProcessingUrlpermitAlldefaultSuccessUrlfailureUrl...
And other methods are defined here.
Finally, let's take a look at FormLoginConfigurer.
2.2.3 FormLoginConfigurer
FormLoginConfigurer is defined as making it clear that the generics in AbstractAuthenticationFilterConfigurer are UsernamePasswordAuthenticationFilter, that is, the filter we are going to configure here is UsernamePasswordAuthenticationFilter.
FormLoginConfigurer overrides the init method to configure the default login page. The rest is basically from the parent class and hasn't changed much.
In addition, many of the things we configure every day also come from here:
OK, this is the configuration class FormLoginConfigurer. The filter corresponding to FormLoginConfigurer is UsernamePasswordAuthenticationFilter. Friends can analyze other xxxConfigurer by themselves, and each xxxConfigurer corresponds to a different Filter.
This is the end of "how to configure SecurityConfigurer". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.