Spring Security --- Custom Filter

  • Introduction
  • Any Spring web application is essentially just a servlet
  • Security Filter filters every incoming HTTP request before the HTTP request reaches your Controller
  • Filter request filter can help filter HttpServletRequest request and HttpServletResponse response
  • In the custom Filter filter, the request can be filtered, and the return can also be processed accordingly, and the custom business logic processing can be realized in the method
  • What Spring Security itself does is to register a series of Filters in the Spring container
  • When these Filters detect a URL request that meets the conditions, they will perform their defined processing
  • Default Filter analysis
  • Security itself provides some Filters by default to complete its various functions
  • Security's default Filter entry is in the HttpSecurity object
  • In the HttpSecurity object, what is actually provided is the configuration class of each default Filter
  • Control the configuration of each attribute of the corresponding Filter through the configuration class
  • After the configuration is complete, load the Filter into the FilterChain in HttpSecurity
  • The following default Filter and its configuration classes are provided in HttpSecurity:

  • The default Filter is not all loaded when the HttpSecurity object is initialized, but loaded according to user customization
  • Add a custom Filter to the custom Spring Security configuration class
  • Custom Filter class

  • Why inherit from the OncePerRequestFilter class
  • OncePerRequestFilter is an abstract filter class in Spring Boot. The function of this class is to inherit the implementation and perform filtering only once per request.
  • Configure myFilter in the custom spring security configuration class
  • The implementation of Filter uses the chain of responsibility pattern in the design pattern
  • When adding a custom filter, there are many ways, you can specify to add a custom filter before or after a specified filter, how to implement it depends on the user's own choice
  • 1- Inject the bean object of the custom Filter

  • 2- Add the custom Filter bean object before the user login authentication verification filter in the filter chain

  • 3-Start the project to see if the Filter is effective, send a random request, and see that the defined myFilter is executed, you can add your own logic implementation in this filter

  • Complete configuration class code

Guess you like

Origin blog.csdn.net/weixin_59624686/article/details/131226517