一、SecurityConfig
在之前的文章中,我们从底层源码的层面了解到,要接管Spring Security的配置,就必须继承WebSecurityConfigurerAdapter,并加上@EnableWebSecurity注解。
一个比较完整的SecurityConfig配置如下:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Lazy
private UserDetailsServiceImpl userDetailsServiceImpl;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsServiceImpl);
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors(withDefaults())
.csrf().disable()
.authorizeRequests()
.antMatchers(SecurityConstants.SWAGGER_WHITELIST).permitAll()
.antMatchers(SecurityConstants.H2_CONSOLE).permitAll()
.antMatchers(HttpMethod.POST, SecurityConstants.SYSTEM_WHITELIST).permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JwtAuthorizationFilter(authenticationManager(), stringRedisTemplate))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.exceptionHandling()
.authenticationEntryPoint(new JwtAuthenticationEntryPoint())
.accessDeniedHandler(new JwtAccessDeniedHandler());
http.headers().frameOptions().disable();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
org.springframework.web.cors.CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(singletonList("*"));
configuration.setAllowedHeaders(singletonList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT", "OPTIONS"));
configuration.setExposedHeaders(singletonList(SecurityConstants.TOKEN_HEADER));
configuration.setAllowCredentials(false);
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
二、详细讲解
而WebSecurityConfigurerAdapter 有三个重要的configure 可以覆写,一个与验证相关的AuthenticationManagerBuilder,另外两个是与Web 相关的HttpSecurity 和WebSecurity。
- AuthenticationManagerBuilder : 用来
配置全局的验证资讯 ,也就是AuthenticationProvider 和UserDetailsService。 - WebSecurity : 用来
配置全局忽略的规则,如静态资源、是否Debug、全局的HttpFirewall、SpringFilterChain 配置 、privilegeEvaluator、expressionHandler、securityInterceptor,启动HTTPS等 - HttpSecurity : 用来
配置各种具体的验证机制规则 ,如OpenIDLoginConfigurer、AnonymousConfigurer、FormLoginConfigurer、HttpBasicConfigurer 等。
参考文章
|