1. Introduction

Today we are going to further study how the custom configure Spring Security we have repeatedly mentioned WebSecurityConfigurerAdapter, And we know the Spring automatic configuration of the Boot is actually passed under the automatic configuration package SecurityAutoConfiguration total configuration class imported Spring Boot Web security configuration classes SpringBootWebSecurityConfiguration to configuration. So we took it out. If you are still confused, check out Spring Security at https://felord.cn.

2. Customize the Spring Boot Web security configuration class

We use our best Ctrl + C and Ctrl + V to copy the source code of SpringBootWebSecurityConfiguration, We custom CustomSpringBootWebSecurityConfiguration named:

@Configuration @ConditionalOnClass(WebSecurityConfigurerAdapter.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) public class CustomSpringBootWebSecurityConfiguration { @Configuration @Order(SecurityProperties.BASIC_AUTH_ORDER) static class DefaultConfigurerAdapter extends WebSecurityConfigurerAdapter {  @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); } @Override public void configure(WebSecurity web) throws Exception { super.configure(web); } @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); }}}Copy the code

Some of you may have noticed that I overrode (@override) the three methods in the DefaultConfigurerAdapter above. We usually customize our secure access policies by customizing these three methods.

2.1 Authentication Manager Configuration Method

Void the configure (AuthenticationManagerBuilder auth) used to configure the authentication manager the AuthenticationManager. It handles all UserDetails, including the PasswordEncoder. You can use UserDetail in Spring Security if you don’t know. AuthenticationManager is not covered in this article, there will be a special article on it later. Can be learned through the Spring Security Practice series.

2.2 Core Filter Configuration Method

Void configure(WebSecurity web) configures WebSecurity. The WebSecurity is based on the Servlet Filter used to configure springSecurityFilterChain. And springSecurityFilterChain is delegated to the Spring Security core filter Bean DelegatingFilterProxy. You can find the logic in WebSecurityConfiguration. Ignoring () we generally don’t customize WebSecurity too much, and use the ignoring() method instead to ignore Spring Security’s control of static resources.

2.3 Security Filter Chain Configuration method

Void configure(HttpSecurity HTTP) This is the one we use most, to configure HttpSecurity. HttpSecurity is used to build a SecurityFilterChain SecurityFilterChain. The SecurityFilterChain is finally injected into the core filter. HttpSecurity has a number of configurations that we need. We can use it to customize security access policies. So let’s do a separate chapter on this thing.

3. HttpSecurity configuration

HttpSecurity will be the focus of the next few articles, and we’ll actually use it to implement some utility features. So this paper will focus on it.

3.1 Default Configuration

      protected void configure(HttpSecurity http) throws Exception {
          logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
  
          http
              .authorizeRequests()
                  .anyRequest().authenticated()
                  .and()
              .formLogin().and()
              .httpBasic();
      }Copy the code

The above is the default configuration of Spring Security in Spring Boot. With the above configuration, your application has the following functions:

  • All requested access needs to be authorized.
  • useformForm to log in (default path is/login), the landing page we’ve seen in the last few posts.
  • To preventCSRFThe attack,XSSAttack.
  • To enable theHTTP Basiccertification

3.2 Interpretation of common methods

HttpSecurity uses the Builder construction method to flexibly formulate access policies. HttpSecurity was first configured based on XML tags. JavaConfig is now mostly used. The commonly used methods are interpreted as follows:

methods instructions
openidLogin() For OpenID-based authentication
headers()

Add security headers to the response, such as simple XSS protection
cors() Configuring Cross-domain Resource Sharing (CORS)
sessionManagement() Allows session management to be configured
portMapper() Allows the configuration of a PortMapper(HttpSecurity#(getSharedObject(class))), Other objects that provide SecurityConfigurer use PortMapper to redirect from HTTP to HTTPS or from HTTPS to HTTP. By default, Spring Security uses a PortMapperImpl to map HTTP port 8080 to HTTPS port 8443 and HTTP port 80 to HTTPS port 443
jee() Configure container-based preauthentication. In this case, authentication is managed by the Servlet container
x509() Configure X509 – based authentication
rememberMe Allows configuration of “Remember me” authentication
authorizeRequests() Allows restricted access based on the use of HttpServletRequest
requestCache() Allows request caching to be configured
exceptionHandling() Allows configuration error handling
securityContext() Set the management of the SecurityContext on the SecurityContextHolder between HttpServletRequests. When using WebSecurityConfigurerAdapter, it will be automatically used
servletApi() Integrate the HttpServletRequest method with the values found on it into the SecurityContext. When using WebSecurityConfigurerAdapter, it will be automatically used
csrf() Add CSRF support, using WebSecurityConfigurerAdapter, enabled by default
logout() Added support for logging out. When using WebSecurityConfigurerAdapter, it will be automatically used. By default, access the URL “/ logout”, invalidate the HTTP Session to clear the user, clear any #rememberMe() authentication that has been configured, clear SecurityContextHolder, and then redirect to “/login? Success”
anonymous() Allows configuring the representation of anonymous users. When combined with WebSecurityConfigurerAdapter use, it will be automatically used. By default, anonymous users will use the org. Springframework. Security. The authentication. AnonymousAuthenticationToken said, and contains a character “ROLE_ANONYMOUS”
formLogin() Specifies support for form-based authentication. If FormLoginConfigurer#loginPage(String) is not specified, the default loginPage is generated
oauth2Login() Configure authentication according to an external OAuth 2.0 or OpenID Connect 1.0 provider
requiresChannel() Configure channel security. For this configuration to be useful, at least one mapping to the desired channel must be provided
httpBasic() Configure Http Basic authentication
addFilterBefore() Adds a Filter before the specified Filter class
addFilterAt() Adds a Filter at the specified Filter class location
addFilterAfter() Adds a Filter after the specified Filter class
and() The connector connected to the above policies is used to combine security policies. It actually means “and”

4. To summarize

So far, we’ve learned a lot about Spring Security from the beginning to the end. We have started to customize to achieve some practical functions, in the later articles we will combine the actual development scenarios for some practical operations. Please follow the public account “Felordcn” for the first time to get related tutorials.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn