In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what is a SpringSecurity filter". In daily operation, I believe many people have doubts about what a SpringSecurity filter is. The editor consulted all kinds of data and sorted out a simple and easy-to-use method of operation. I hope it will be helpful to answer the questions of "what is a SpringSecurity filter?" Next, please follow the editor to study!
Pre-knowledge
We know that Spring Security completes its core process through Filter. But:
What kind of Filter does Spring Security have?
How is this Filter injected into the container?
How do we customize our own Filter?
Web.xml configuration
As we have already explained, at the beginning, if we want to configure Filter, it is usually through web.xml:
Add Filter to deleFilter org.springframework.web.filter.DelegatingFilterProxy targetBeanName spring-bean-name deleFilter / * SpringBoot
Custom Filter can be injected into SpringBoot through @ WebFilter and @ ServletComponentScan annotations.
@ WebFilter (filterName = "myFilter", urlPatterns = "/ *") public class MyFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) {} @ Override public void destroy () {}} @ SpringBootApplication@ServletComponentScan (basePackages = "vip.mycollege.filter") public class StartApplication {public static void main (String [] args) {SpringApplication.run (StartApplication.class, args);}}
You can also inject custom Filter through FilterRegistrationBean.
@ Configurationpublic class FilterConfig {@ Bean public FilterRegistrationBean filterRegistrationBean () {FilterRegistrationBean bean = new FilterRegistrationBean (); bean.setFilter (new MyFilter ()); bean.addUrlPatterns ("/ *"); return bean;}}
It can also be done through DelegatingFilterProxyRegistrationBean.
@ Configurationpublic class FilterConfig {@ Bean ("proxyFilter") public Filter filter () {return new Filter () {@ Override public void init (javax.servlet.FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest request, ServletResponse response FilterChain chain) {} @ Override public void destroy () {} @ Bean public DelegatingFilterProxyRegistrationBean delegatingFilterProxyRegistrationBean () {DelegatingFilterProxyRegistrationBean bean = new DelegatingFilterProxyRegistrationBean ("proxyFilter") Bean.addUrlPatterns ("/ *"); return bean;}}
Both DelegatingFilterProxyRegistrationBean and FilterRegistrationBean inherit AbstractFilterRegistrationBean, and the name indicates that it is a RegistrationBean, which means it will be injected when the Servlet container starts.
DelegatingFilterProxyRegistrationBean registers a DelegatingFilterProxy in the Servlet container to proxy the Filter bean of a specified name in the Spring IoC container.
FilterChainProxy
SpringBoot has an automatic configuration class for SecurityFilterAutoConfiguration, so it configures a DelegatingFilterProxyRegistrationBean with name as springSecurityFilterChain. The url-pattern for this class defaults to / *, which means that all requests are filtered.
Name is springSecurityFilterChain. What kind of ghost is it?
The answer is FilterChainProxy.
This class is registered in the registerFilterChainProxyIfNecessary method of HttpSecurityBeanDefinitionParser.
HttpSecurityBeanDefinitionParser is also a BeanDefinitionParser, so it builds the Filter class through the parse method.
The whole process is now clear:
SpringBoot created a DelegatingFilterProxyRegistrationBean by automatically configuring the class.
DelegatingFilterProxyRegistrationBean registers a DelegatingFilterProxy when Servlet starts
By default, DelegatingFilterProxy will intercept all requests and submit a FilterChainProxy aliased as springSecurityFilterChain
FilterChainProxy is holding a list of SecurityFilterChain
SecurityFilterChain itself holds a list of Filter. You can use match to find the Request that matches the url and submit it to filters for processing.
In addition to holding the filter, FilterChainProxy has a built-in StrictHttpFirewall and HTTP firewall by default, which adopts strict mode and rejects any suspicious request by throwing an exception RequestRejectedException.
Now we know how Spring Security collects and uses Filter.
But what kind of Filter did Spring Security get behind our back?
I just want to say a lot, and it's easy to know what is there. Hit a breakpoint in FilterChainProxy, debug, and look at the list of filters in the filterChains variable to see what filter there are.
By default, filterChains has only one filte, which is DefaultSecurityFilterChain. If you look at the name, you can see that this is a SecurityFilterChain. It contains a list of Filter. By default, it has:
WebAsyncManagerIntegrationFilter: integration with WebAsyncManager that handles asynchronous request mapping
SecurityContextPersistenceFilter: save before request and clear the security context in SecurityContextHolder after request
HeaderWriterFilter: add header information to the response
CsrfFilter: handling cross-site request forgery
LogoutFilter: handling logout
UsernamePasswordAuthenticationFilter: handling form-based login
DefaultLoginPageGeneratingFilter: if no login page is configured, generate the default login page
DefaultLogoutPageGeneratingFilter: if there is no logout page, generate the default logout page
BasicAuthenticationFilter: handling HTTP BASIC authentication
RequestCacheAwareFilter: cache for processing requests
SecurityContextHolderAwareRequestFilter: wraps the request object request
AnonymousAuthenticationFilter: check whether Authentication exists in SecurityContextHolder, and provide an anonymous Authentication if it does not exist
SessionManagementFilter: filter for managing session
ExceptionTranslationFilter: handling AccessDeniedException and AuthenticationException exceptions
FilterSecurityInterceptor: related to permission verification
Important FilterUsernamePasswordAuthenticationFilter
UsernamePasswordAuthenticationFilter itself has nothing to say, it is just a Filter, but because it is used a lot, so say it.
Filter must first look at the doFilter method. The main authentication logic of UsernamePasswordAuthenticationFilter is attemptAuthentication:
@ Overridepublic Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {if (this.postOnly & &! request.getMethod (). Equals ("POST")) {throw new AuthenticationServiceException ("Authentication method not supported:" + request.getMethod ());} String username = obtainUsername (request); username = (username! = null)? Username: ""; username = username.trim (); String password = obtainPassword (request); password = (password! = null)? Password: ""; UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken (username, password); setDetails (request, authRequest); return this.getAuthenticationManager () .authenticate (authRequest);}
It is very simple to get the fields of username and password from request, encapsulate them into UsernamePasswordAuthenticationToken, and throw them to AuthenticationManager to perform authentication. Of course, the final authentication logic must be an AuthenticationProvider execution like DaoAuthenticationProvider.
FilterSecurityInterceptor
FilterSecurityInterceptor is mainly used for permission verification, and the specific authentication logic is mainly in AbstractSecurityInterceptor.
FilterSecurityInterceptor is also a Filter, so let's first look at the doFilter method and call invoke:
Public void invoke (FilterInvocation filterInvocation) throws IOException, ServletException {/ / avoid double checking if (isApplied (filterInvocation) & & this.observeOncePerRequest) {filterInvocation.getChain () .doFilter (filterInvocation.getRequest (), filterInvocation.getResponse ()); return } / / the first call, first set the flag to avoid repeated calls to if (filterInvocation.getRequest ()! = null & & this.observeOncePerRequest) {filterInvocation.getRequest () .setAttribute (FILTER_APPLIED, Boolean.TRUE) } / / before the business logic is called, the main purpose of performing the check authentication operation is to complete InterceptorStatusToken token = super.beforeInvocation (filterInvocation); try {/ / execute the specific business logic filterInvocation.getChain (). DoFilter (filterInvocation.getRequest (), filterInvocation.getResponse () } finally {super.finallyInvocation (token);} / / after the business logic is called, it mainly deals with the returned result super.afterInvocation (token, null);}
FilterInvocation is a simple package of FilterInvocation, ServletResponse, and FilterChain.
We can see that the logic of the whole invoke is very clear, much like the around structure of AOP.
ExceptionTranslationFilter
The logic of ExceptionTranslationFilter is a little strange, mainly to handle AccessDeniedException and AuthenticationException exceptions. But it does not handle the exception generated in front of it, but the exception generated by the Filter behind it, because the Filter in front of it cannot reach it if it is abnormal.
Behind it, there is only FilterSecurityInterceptor by default, which mainly produces AccessDeniedException authorization exceptions. AuthenticationException is because there is a process of re-authentication.
Filter
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
ChannelProcessingFilter
ConcurrentSessionFilter
HeaderWriterFilter
CorsFilter
CsrfFilter
LogoutFilter
OAuth3AuthorizationRequestRedirectFilter
Saml2WebSsoAuthenticationRequestFilter
X509AuthenticationFilter
AbstractPreAuthenticatedProcessingFilter
CasAuthenticationFilter
OAuth3LoginAuthenticationFilter
Saml2WebSsoAuthenticationFilter
UsernamePasswordAuthenticationFilter
ConcurrentSessionFilter
OpenIDAuthenticationFilter
DefaultLoginPageGeneratingFilter
DefaultLogoutPageGeneratingFilter
DigestAuthenticationFilter
BearerTokenAuthenticationFilter
BasicAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
JaasApiIntegrationFilter
RememberMeAuthenticationFilter
AnonymousAuthenticationFilter
OAuth3AuthorizationCodeGrantFilter
SessionManagementFilter
ExceptionTranslationFilter
SwitchUserFilter
FilterSecurityInterceptor
At this point, the study on "what is a SpringSecurity filter" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.