Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand SecurityConfigurer

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 "how to understand SecurityConfigurer". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand SecurityConfigurer".

1. SecurityConfigurerSecurityConfigurer

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 should be noted that the parameter type of these two methods is a generic B, that is, a subclass of SecurityBuilder, about SecurityBuilder, which is used to build a filter chain, which Song GE will introduce in the next article.

SecurityConfigurer has three implementation classes:

SecurityConfigurerAdapter

GlobalAuthenticationConfigurerAdapter

WebSecurityConfigurer

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;}

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

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. Brother Song, the other two lines, will also write two articles and introduce them to you.

2. SecurityConfigurerAdapter

The implementation of SecurityConfigurerAdapter can be divided into three main categories:

UserDetailsAwareConfigurer

AbstractHttpConfigurer

LdapAuthenticationProviderConfigurer

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") .password ("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.

So many implementation classes, Brother Song will not introduce them to you one by one. I will choose a commonly used FormLoginConfigurer to give you a detailed introduction. As long as you understand this, the others will be easy to understand.

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, there is 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. In fact, in Song GE's previous article, and vhr (https://github.com/lenve/vhr) project, you can also use the withObjectPostProcessor method (of course, you can also use addObjectPostProcessor The final effect is the same.

2.2.2 AbstractAuthenticationFilter

The ConfigurerAbstractAuthenticationFilterConfigurer 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:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

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:

LoginPage

LoginProcessingUrl

PermitAll

DefaultSuccessUrl

FailureUrl

...

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:

Thank you for your reading, the above is the content of "how to understand SecurityConfigurer", after the study of this article, I believe you have a deeper understanding of how to understand SecurityConfigurer, 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report