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

Example Analysis of loading and execution process of Spring Security filter chain

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the example analysis of the loading and execution process of Spring Security filter chain, which is very detailed and has a certain reference value. Interested friends must read it!

Principle of Spring Security implementation

Spring Security adopts the ideas of IoC and AOP, based on the security framework implemented by Servlet filter, provides identity confirmation and authorization processing for Web requests and method calls, and provides integration with other libraries to simplify their use, avoid code coupling, and reduce a lot of repetitive code work.

In the previous web.xml, we wrote like this.

SpringSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy springSecurityFilterChain / *

After the Spring Boot project, we introduce the Spring Security dependency and do nothing, the startup project Spring Security takes effect and the access request is intercepted.

Spring Boot provides an automated configuration scheme for Spring Security, and you can use Spring Security with less configuration.

So how does the filter chain load and intercept?

1. Load the Spring Security filter chain and register the filter named springSecurityFilterChain

When the Spring Boot project starts, the SecurityFilterAutoConfiguration class loads the DelegatingFilterProxyRegistrationBean registration filter, named springSecurityFilterChain.

Note: springSecurityFilterChain names are always written to death.

After the DelegatingFilterProxyRegistrationBean registration is successful, the filter is loaded into the registry.

After the registrar registers all the filters, a DelegatingFilterProxy proxy object is generated for each filter and registered in IoC.

2. View the DelegatingFilterProxy class

When we visit the project, we enter the doFilter method of the DelegatingFilterProxy class.

The DelegatingFilterProxy class is also essentially a Filter, which indirectly implements the Filter interface, but actually calls the proxy Filter implementation class obtained from the Spring container in doFilter.

The returned FilterChainProxy object.

Thus, the DelegatingFilterProxy class gets a FilterChainProxy filter by the name springSecurityFilterChain, and finally executes the doFilter method of the filter.

1) verify that springSecurityFilterChain nouns cannot be modified

View the initDelegate method.

3. View the FilterChainProxy class

The FilterChainProxy class is also essentially a Filter, so take a look at the doFilter method. Pay attention to the properties in this class.

Public class FilterChainProxy extends GenericFilterBean {private static final Log logger = LogFactory.getLog (FilterChainProxy.class); private static final String FILTER_APPLIED = FilterChainProxy.class.getName () .concat (".APPLIED"); / / filter chain private List filterChains; private FilterChainProxy.FilterChainValidator filterChainValidator; private HttpFirewall firewall

View the doFilterInternal method.

Are you surprised? All 15 filters are here!

3.2View the getFilters method.

It turns out that these filters are encapsulated in SecurityFilterChain objects.

4 View the SecurityFilterChain interface

The SecurityFilterChain class is an interface, and the implementation class has only one DefaultSecurityFilterChain class.

The constructor of the DefaultSecurityFilterChain class, which initializes the List filters, is put in by passing parameters.

When was the filter chain parameter passed in?

5 View the SpringBootWebSecurityConfiguration class

The Spring Security filter chain is created to be automatically configured by Spring boot, and the injection is created by the SpringBootWebSecurityConfiguration class.

View the WebSecurityConfigurerAdapter class.

Then the HttpSecurity object is injected. HttpSecurity can be understood as the http core configuration of Spring Security, an important method of storing filter chain in Spring Security, request matching path and other related authentication authorization.

Then start creating the Spring Security filter chain, which is handed over to Spring Boot automatic configuration, with a total of 15 filters.

Use OrderedFilter as the proxy and set the order property.

After the addition is completed, these filters are re-encapsulated as DefaultSecurityFilterChain objects.

Finally, the securityFilterChains property is maintained in the springSecurityFilterChain,WebSecurityConfiguration through the WebSecurityConfiguration configuration load, which stores all the filters in the filter chain.

Summary:

Spring boot registers the filter with the name springSecurityFilterChain through DelegatingFilterProxyRegistrationBean, generates a DelegatingFilterProxy proxy object and registers it with IoC. Finally, the doFilter of the FilterChainProxy filter is actually called to get the Spring Security filter chain.

Spring Security's filter chain is encapsulated in the SecurityFilterChain interface at the bottom.

Second, the execution process of the filter chain 1. Call the OncePerRequestFilter filter

The first thing to enter is the OncePerRequestFilter filter.

The purpose of OncePerRequestFilter is to ensure that only one filter is passed in a request and does not need to be executed repeatedly.

It goes into the invokeDelegate method in the DelegatingFilterProxy proxy object, and what is actually executed is the doFilter method of the FilterChainProxy filter.

2. View the FilterChainProxy filter

View the doFilterInternal method in the FilterChainProxy filter.

Then first go to the doFilterInternal method in FilterChainProxy.

The getFilters method is called in the doFilterInternal method, and all interceptors are taken out of the filter chain.

Then create a VirtualFilterChain object, a virtual filter chain, and execute the doFilter method in it. Use a filter to filter the current request layer by layer.

3. View the FilterSecurityInterceptor filter

Finally, you go into the FilterSecurityInterceptor filter, which is the last filter in the filter chain, the invoke method.

First call the beforeInvocation method of the parent class, then call the doFilter method of filterChain, and then call the finallyInvocation and afterInvocation methods of the parent class.

In the beforeInvocation method, if the current request is not authenticated, an Access is denied exception is thrown, which is handled by the ExceptionTranslationFilter filter. If the exception thrown is AuthenticationException, the method sendStartAuthentication method is executed.

Finally, the commence method of EntryPoint is called, and the exception is issued.

Third, Spring Security common filter

1 、 WebAsyncManagerIntegrationFilter

Org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter

It is mainly used to integrate SecurityContext into WebAsyncManager in the asynchronous execution mechanism of Spring.

2 、 SecurityContextPersistenceFilter

Org.springframework.security.web.context.SecurityContextPersistenceFilter

The main purpose of this method is to use SecurityContextRepository to save or update a SecurityContext in session, and give the SecurityContext to future filters to establish the required context for subsequent filter.

The authentication and permission information of the current user is stored in SecurityContext.

3 、 HeaderWriterFilter

Org.springframework.security.web.header.HeaderWriterFilter

The main purpose of this method is to add the corresponding information to the requested Header, which can be controlled by security:headers inside the http tag.

4 、 CsrfFilter

Org.springframework.security.web.csrf.CsrfFilter

Csrf is also called cross-domain request forgery. SpringSecurity verifies whether it contains the token information of the system-generated csrf for all post requests.

If not, an error is reported. Play the effect of preventing csrf attacks.

5 、 LogoutFilter

Org.springframework.security.web.authentication.logout.LogoutFilter

It is mainly used to realize user exit and clear authentication information. Requests with URL of / logout are matched by default.

6 、 UsernamePasswordAuthenticationFilter

Org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

It is mainly used for authentication operations. The default matching URL is / login and must be a POST request.

7 、 DefaultLoginPageGeneratingFilter

Org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter

If no authentication page is specified in the configuration file, a default authentication page is generated by the filter.

8 、 DefaultLogoutPageGeneratingFilter

Org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter

This filter can produce a default exit login page

9 、 BasicAuthenticationFilter

Org.springframework.security.web.authentication.www.BasicAuthenticationFilter

This filter automatically parses the header information in the HTTP request whose header name is Authentication and starts with Basic.

10 、 RequestCacheAwareFilter

Org.springframework.security.web.savedrequest.RequestCacheAwareFilter

A RequestCache is maintained internally through HttpSessionRequestCache for caching HttpServletRequest.

11 、 SecurityContextHolderAwareRequestFilter

Org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter

A package is carried out for ServletRequest, which makes request have more abundant API.

12 、 AnonymousAuthenticationFilter

Org.springframework.security.web.authentication.AnonymousAuthenticationFilter

When the authentication information in SecurityContextHolder is empty, an anonymous user is created and stored in SecurityContextHolder.

In order to be compatible with unlogged-in access, Spring Security also goes through a set of authentication process, which is only an anonymous identity.

13 、 SessionManagementFilter

Org.springframework.security.web.session.SessionManagementFilter

It is mainly used to limit the number of sessions opened by the same user.

14 、 ExceptionTranslationFilter

Org.springframework.security.web.access.ExceptionTranslationFilter

The exception translation filter is located behind the entire springSecurityFilterChain and is used to convert exceptions that occur throughout the link. The ExceptionTranslationFilter filter intercepts the processing AccessDeniedException and AuthenticationException and adds them to the HTTP response.

15 、 FilterSecurityInterceptor

Org.springframework.security.web.access.intercept.FilterSecurityInterceptor

Get the authorization information for the configured resource access, and determine whether it has permissions based on the user information stored in the SecurityContextHolder.

The above is all the contents of the article "sample Analysis of Spring Security filter chain loading and execution process". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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