This is the 23rd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Writing in the front

Spring Security has now been updated to 17 articles. Counting this article, there are already 18 articles. If you are interested, you can click on my profile picture to view the column. We study together,

By the way, the concurrent queue and Security columns are currently in progress. The design patterns column has been completed, and you can check it out if you are interested

Today we are going to talk about filters in Security. Those of you who have read my previous articles should know that Security permissions are implemented through filters. And there is more than one filter. The default is 15. And there’s like 32 of them all. I will share with you one by one after I have studied these filters

The filter

Let’s start with filters. Let’s start by reviewing what the request flow looks like in a Web project, as shown below

Right? The request is initiated from the client (such as a browser) and then traversed through layers of filters to the Servlet, where it is processed by the Servlet.

This is a good time to ask the question: Are the default 15 filters in Spring Security nested between clients and servlets in this way?

The answer is definitely not! Let’s analyze it

The Filter in the figure above can be called Web Filter and the Filter in Spring Security can be called Security Filter. The relationship between them is shown as follows:

As you can see, Spring Security Filter is not directly embedded in the Web Filter, but is managed by FilterChainProxy. The FilterChainProxy itself is embedded in the Web Filter via the DelegatingFilterProxy proxy Filter provided by Spring.

Multiple filter chains

This is a single filter chain. In fact, in Spring Security, there can be multiple filter chains.

The following code configuration is not multiple filter chains?

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("admin")
            .antMatchers("/user/**").hasRole("user")
            .anyRequest().authenticated()
            ...
            .csrf().disable();
}
Copy the code

I’m sure you’ve all seen this configuration, but it’s not a chain of filters, it’s a chain of filters. Because whether /admin/** or /user/**, the filter is the same, but different path judgment conditions are different.

If the system has multiple filter chains, these filter chains will be divided in FilterChainProxy, as shown below:

As you can see, when the request arrives at FilterChainProxy, FilterChainProxy forwards the request to different Spring Security Filters based on the requested path. Different Spring Security Filters correspond to different Filters, meaning that different requests will pass through different Filters.

Under normal circumstances, we configure a filter chain, how to configure multiple filter chains? Let me give you a simple example:

@Configuration
public class SecurityConfig {
    @Bean
    protected UserDetailsService userDetailsService(a) {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("shushi").password("{bcrypt}$2a$10$Sb1gAUH4wwazfNiqflKZve4Ubh.spJcxgHG8Cp29DeGya5zsHENqi").roles("admin"."aaa"."bbb").build());
        manager.createUser(User.withUsername("yn").password("{noop}123").roles("admin").build());
        manager.createUser(User.withUsername("A little something.").password("{MD5}{Wucj/L8wMTMzFi3oBKWsETNeXbMFaHZW9vCK9mahMHc=}4d43db282b36d7f0421498fdc693f2a2").roles("user"."aaa"."bbb").build());
        return manager;
    }

    @Configuration
    @Order(1)
    static class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/foo/**")
                    .authorizeRequests()
                    .anyRequest().hasRole("admin") .and() .csrf().disable(); }}@Configuration
    @Order(2)
    static class DefaultWebSecurityConfig2 extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/bar/**")
                    .authorizeRequests()
                    .anyRequest().hasRole("user") .and() .formLogin() .permitAll() .and() .csrf().disable(); }}}Copy the code

Let’s analyze the above code one by one:

  • First of all, SecurityConfig no longer need to inherit from WebSecurityConfigurerAdapter, just as a normal class, add @ the Configuration notes.

  • Provide the UserDetailsService instance, which acts as our data source.

  • Create a static inner class inheritance WebSecurityConfigurerAdapter class, at the same time, use the @ Configuration comments mark a static inner class is a Configuration, Configuration class inside of the code is the same as before

  • Each static inner class is a configuration of a chain of filters

  • Note that in the static inner class, I didn’t start with http.authorizerequests (). The http.authorizerequests () configuration indicates that the path to the filter chain is /. In the static inner class, I use http.antmatcher (“/bar/”) to enable the configuration, which limits the current filter chain to /bar/**.

  • When there are multiple filter chains, there must be a priority issue, so the @order (2) annotation on the configuration class of each filter chain marks the priority.

OK so much for learning about Spring Security’s multiple filters. See you next time!

overtones

Thank you for reading, and if you feel like you’ve learned something, you can like it and follow it. Also welcome to have a question we comment below exchange

Come on! See you next time!

To share with you a few I wrote in front of a few SAO operation

Copy object, this operation is a little SAO!

Dry! SpringBoot uses listening events to implement asynchronous operations