(C) Spring Security - core configuration Interpretation

Abstract: Original Source  https://www.cnkirito.moe/spring-security-3/  "Xu" welcome to reprint reserved summary, thank you!



Previous article "Spring Security (two) -Guides", by using the configuration of Spring Security Spring Security is to know how to protect our applications on this article to a configuration to do an analysis.

3 core configuration Interpretation

3.1 Features

This is the configuration items Spring Security Getting Started Guide:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http
          .authorizeRequests()
              .antMatchers("/", "/home").permitAll()
              .anyRequest().authenticated()
              .and()
          .formLogin()
              .loginPage("/login")
              .permitAll()
              .and()
          .logout()
              .permitAll();
  }

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      auth
          .inMemoryAuthentication()
              .withUser("admin").password("admin").roles("USER");
  }
}

 

In addition to "/", "/ home" (Home), "/ login" (login), "/ logout" (write-off), the other paths have to be authenticated. After the above configuration javaconfig, our application will have the following functions:

  • Specify "/ login" the path to the login page when the unauthorized user tries to access any protected resource, will jump to the "/ login".
  • Specifies the default "/ logout" to logout page
  • A configuration memory in the user authentication device, using admin / admin as the user name and password, with USER role

3.2 @EnableWebSecurity

Our own definition configuration class WebSecurityConfig added @EnableWebSecurity comment, also inherited WebSecurityConfigurerAdapter. You might be wondering who's bigger role, no doubt @EnableWebSecurity play a decisive role in the configuration, it is actually a combination comment.

@Import({ WebSecurityConfiguration.class, // <2>
      SpringWebMvcImportSelector.class }) // <1>
@EnableGlobalAuthentication // <3>
@Configuration
public @interface EnableWebSecurity {
   boolean debug() default false;
}

 

<1>  SpringWebMvcImportSelectoraction is to determine whether the current environment comprising SpringMVC, can be used as spring security environment in a non-spring, arranged to avoid repetition DispatcherServlet, so distinguished using this annotation. @Import springboot is arranged to provide comments for introducing external, it can be understood as: @EnableWebSecurity annotation activated configuration class @Import annotations contained.

<2>  WebSecurityConfigurationAs the name implies, it is used to configure the secure web, the following sections will detail.

<3>  @EnableGlobalAuthenticationannotated source as follows:

@Import(AuthenticationConfiguration.class)
@Configuration
public @interface EnableGlobalAuthentication {
}

 

In other words: @EnableWebSecurity completed work is loaded WebSecurityConfiguration, AuthenticationConfiguration these two core configuration class, and it has the spring segregation of duties in order to configure security information security, authentication information is configured in two parts. Note that the same point in @Import, it actually activates AuthenticationConfiguration such a configuration class is used to configure the authentication-related core classes.

WebSecurityConfiguration

In this configuration class, there is a very important Bean is registered.

@Configuration
public class WebSecurityConfiguration {

    //DEFAULT_FILTER_NAME = "springSecurityFilterChain"
    @Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
    public Filter springSecurityFilterChain() throws Exception {
        ...
    }

 }

 

<!-- Spring Security -->
   <filter>
       <filter-name>springSecurityFilterChain</filter-name>
       <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
   </filter>

   <filter-mapping>
       <filter-name>springSecurityFilterChain</filter-name>
       <url-pattern>/*</url-pattern>
   </filter-mapping>

 

And after springboot integrated, configured such XML is substituted java. WebSecurityConfiguration completed in a statement springSecurityFilterChain role, and ultimately to DelegatingFilterProxy this proxy class, responsible for intercepting requests (note that this class is not DelegatingFilterProxy spring security package, but in the web package, spring a proxy model to achieve security filtering decoupling). Before springboot not in use, most people should "springSecurityFilterChain" the term will not be unfamiliar, he is the core of the filter spring security of the entire certification entrance. , You want to enable spring security, perform the following configurations in web.xml once in an XML configuration:

AuthenticationConfiguration

@Configuration
@Import(ObjectPostProcessorConfiguration.class)
public class AuthenticationConfiguration {

      @Bean
    public AuthenticationManagerBuilder authenticationManagerBuilder(
            ObjectPostProcessor<Object> objectPostProcessor) {
        return new AuthenticationManagerBuilder(objectPostProcessor);
    }

      public AuthenticationManager getAuthenticationManager() throws Exception {
        ...
    }

}

 

3.3 WebSecurityConfigurerAdapter main task AuthenticationConfiguration, and that is responsible for generating the global authentication manager AuthenticationManager. Remember the "Spring Security (a) -Architecture Overview", we introduce the Spring Security's authentication system, AuthenticationManager is the core of the Identity Manager.

Adapter model is widely used in the spring, the use of Adapter in the configuration of the benefits is that we can selectively configure want to modify that part of the configuration, without covering other non-related configuration. WebSecurityConfigurerAdapter we can choose the content you want to modify, to rewrite, and it offers three configure overloaded methods, it is our main concern:

WebSecurityConfigurerAdapter中的configureWebSecurityConfigurerAdapter中的configure

You can know the parameters, respectively, it is AuthenticationManagerBuilder, WebSecurity, HttpSecurity personalized configuration.

HttpSecurity common configuration

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/resources/**", "/signup", "/about").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
                .anyRequest().authenticated () 
                .and()
            (.formLogin)
                .usernameParameter("username")
                .passwordParameter("password")
                .failureForwardUrl("/login?error")
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/index")
                .permitAll()
                .and()
            .httpBasic()
                .disable();
    }
}

 

authorizeRequests () configuration path to intercept, indicate permission to access the path corresponding to the role, the authentication information. The above is a typical configuration Java Configuration configuration HttpSecurity, wherein http as the root of the configuration, each of a and () corresponds to a configuration of a module (equivalent to the end tag xml configuration), and and () returns HttpSecurity itself, Thus it can be configured continuously. Meaning their configuration is also very easy to speculate through the variable itself,

  • formLogin () corresponding to the relevant configuration forms authentication
  • logout () corresponding to the configuration of the logout
  • httpBasic () you can configure basic login
  • etc

They represent the http request related to security configuration, without exception, these configuration items returned Configurer class, and all the http configuration can be learned by looking at HttpSecurity main method:

http://kirito.iocoder.cn/QQ%E5%9B%BE%E7%89%8720170924223252.pnghttp://kirito.iocoder.cn/QQ%E5%9B%BE%E7%89%8720170924223252.png

You need to have some knowledge in order to fully grasp all of the configuration of the http protocol, however, springboot spring security and autoconfiguration enough to use. Each of which Configurer (egFormLoginConfigurer, CsrfConfigurer) is a refinement of configuration items HttpConfigurer.

WebSecurityBuilder

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/resources/**");
    }
}

 

AuthenticationManagerBuilder以笔者的经验,这个配置中并不会出现太多的配置信息。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser("admin").password("admin").roles("USER");
    }
}

 

细心的朋友会发现,在前面的文章中我们配置内存中的用户时,似乎不是这么配置的,而是:想要在WebSecurityConfigurerAdapter中进行认证相关的配置,可以使用configure(AuthenticationManagerBuilder auth)暴露一个AuthenticationManager的建造器:AuthenticationManagerBuilder 。如上所示,我们便完成了内存中用户的配置。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }
}

 

If your application there is only a WebSecurityConfigurerAdapter, then the gap between them can be ignored, the method name can be seen from the difference between the two: use @Autowired injected AuthenticationManagerBuilder is global identity, a scope can span multiple WebSecurityConfigurerAdapter and the impact on the safety control Method; and  protected configure()in a manner similar to the anonymous inner classes, its scope a limited internal WebSecurityConfigurerAdapter. About this difference, reference may issue I have raised the Spring-Security # issues4571 . The official document also shows the configuration of multiple WebSecurityConfigurerAdapter scenes and demo, will be interpreted in a future article in this series
.

Guess you like

Origin www.cnblogs.com/lywJ/p/10984965.html