This article will detail the WebSecurityConfigurerAdapter in security.
Overview
Today we are going to further learn how to customize Spring Security. We have mentioned WebSecurityConfigurerAdapter many times, and we know that the automatic configuration in Spring Boot is actually the Spring Boot Web Security imported through the SecurityAutoConfiguration general configuration class under the automatic configuration package. Configuration class SpringBootWebSecurityConfiguration to configure.
SpringBootWebSecurityConfiguration source code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package org.springframework.boot.autoconfigure.security.servlet; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration( proxyBeanMethods = false ) @ConditionalOnClass({WebSecurityConfigurerAdapter.class}) @ConditionalOnMissingBean({WebSecurityConfigurerAdapter.class}) @ConditionalOnWebApplication( type = Type.SERVLET ) public class SpringBootWebSecurityConfiguration { public SpringBootWebSecurityConfiguration() { } @Configuration( proxyBeanMethods = false ) @Order(2147483642) static class DefaultConfigurerAdapter extends WebSecurityConfigurerAdapter { DefaultConfigurerAdapter() { } } } |
Common method
WebSecurityConfigurerAdapter class diagram

Common configuration
Let’s paste the common configuration of WebSecurityConfigurerAdapter in the project
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
package cn.wideth.framework.config; import cn.wideth.framework.security.handle.AuthenticationEntryPointImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.web.filter.CorsFilter; import cn.wideth.framework.security.filter.JwtAuthenticationTokenFilter; import cn.wideth.framework.security.handle.LogoutSuccessHandlerImpl; /** * spring security configuration * */ @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * Custom user authentication logic */ @Autowired private UserDetailsService userDetailsService; /** * Authentication failure handling class */ @Autowired private AuthenticationEntryPointImpl unauthorizedHandler; /** * Exit handler class */ @Autowired private LogoutSuccessHandlerImpl logoutSuccessHandler; /** * token authentication filter */ @Autowired private JwtAuthenticationTokenFilter authenticationTokenFilter; /** * Cross domain filter */ @Autowired private CorsFilter corsFilter; /** * Solved the inability to directly inject AuthenticationManager * * @return * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * Strong hash hash encryption implementation */ @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } /** * Identity authentication interface */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //Associate database and security here auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } /** * anyRequest | matches all request paths * access | Accessible when SpringEl expression evaluates to true * anonymous | Anonymous can access * denyAll | user cannot access * fullyAuthenticated | The user is fully authenticated and can access (automatic login without remember-me) * hasAnyAuthority | If there are parameters, the parameters represent permissions, any one of them can access * hasAnyRole | If there are parameters, the parameters represent roles, any one of them can access * hasAuthority | If there is a parameter, the parameter represents the authority, then its authority can access * hasIpAddress | If there is a parameter, the parameter represents the IP address, and if the user IP matches the parameter, it can be accessed * hasRole | If there is a parameter, the parameter represents a role, then its role can access * permitAll | User can access arbitrarily * rememberMe | Allow access for users logged in via remember-me * authenticated | user can access after login */ @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity // CSRF disabled because session is not used .csrf().disable() // Authentication failure handling class .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // Based on token, so no session is needed .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() // filter request .authorizeRequests() // Allow anonymous access for login verification code captchaImage .antMatchers("/login", "/captchaImage").anonymous() .antMatchers( HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js" ).permitAll() .antMatchers("/profile/**").permitAll() .antMatchers("/common/download**").permitAll() .antMatchers("/common/download/resource**").permitAll() .antMatchers("/swagger-ui.html").permitAll() .antMatchers("/swagger-resources/**").permitAll() .antMatchers("/webjars/**").permitAll() .antMatchers("/*/api-docs").permitAll() .antMatchers("/druid/**").permitAll() .antMatchers("/flowable/**").permitAll() .antMatchers("/socket/**").permitAll() .antMatchers("/api/common/**").permitAll() .antMatchers("/api/contract/**").permitAll() .antMatchers("/api/project/**").permitAll() .antMatchers("/api/document/**").permitAll() .antMatchers("/api/purchase/**").permitAll() // All requests except the above require authentication .anyRequest().authenticated() .and() .headers().frameOptions().disable(); httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); // add JWT filter httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // add CORS filter httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class); httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class); } /*** * Core filter configuration method * @param web * @throws Exception */ @Override public void configure(WebSecurity web) throws Exception { super.configure(web); } } |
I believe someone has noticed that I have overridden (@Override) three configure methods in the WebSecurityConfigurerAdapter above. We generally customize our security access policy by customizing these three methods.
Authentication Manager Configuration Methods
AuthenticationManagerBuilder (Authentication Manager Builder)
void configure(AuthenticationManagerBuilder auth) is used to configure AuthenticationManager. To put it bluntly, it manages all UserDetails related, including PasswordEncoder passwords, etc. If you are not clear, you can find out through UserDetail in Spring Security. This article does not do a specific analysis and explanation of AuthenticationManager, and there will be a special article about this later.
Common usage
1 2 3 4 5 |
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } |
Core filter configuration method
WebSecurity (WEB security)
void configure(WebSecurity web) is used to configure WebSecurity . And WebSecurity is based on Servlet Filter to configure springSecurityFilterChain . The springSecurityFilterChain is delegated to the Spring Security core filter Bean DelegatingFilterProxy . The related logic can be found in WebSecurityConfiguration. We generally don’t customize WebSecurity too much, and use more of its ignoring() method to ignore Spring Security’s control of static resources.
Security filter chain configuration method
HttpSecurity (HTTP request security processing)
void configure(HttpSecurity http) This is what we use the most to configure HttpSecurity . HttpSecurity is used to build a security filter chain SecurityFilterChain . The SecurityFilterChain is eventually injected into the core filter. HttpSecurity has many configurations that we need. We can use it to customize the security access policy. So we have a separate chapter to explain this stuff.
HttpSecurity configuration
HttpSecurity is the focus of the following articles, and we will actually operate it to achieve some practical functions. So this article will focus on it.
HttpSecurity class diagram

Default Allocation
1 2 3 4 5 6 7 8 9 10 11 12 13 |
protected void configure(HttpSecurity http) throws Exception { this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity)."); ((HttpSecurity)((HttpSecurity((AuthorizedUrl) http. authorizeRequests(). anyRequest()).authenticated(). and()). formLogin(). and()). httpBasic(); } |
The above is the default configuration of Spring Security in Spring Boot. Through the above configuration, your application has the following functions:
- All requested access requires authorization.
- Use the form form to log in (the default path is /login), which is the login page we saw in the previous articles.
- Prevent CSRF attack, XSS attack.
- Enable HTTP Basic Authentication
Summary of this article
This article introduces the knowledge and content related to WebSecurityConfigurerAdapter in detail, and will introduce the knowledge related to HttpSecurity in detail later, which is also the most used place in normal development.