Spring Security 配置
注解@EnableWebSecurity
@EnableWebSecurity 注解用于开启WebSecurity模式,是spring security 用于启用Web安全的注解。
在非Spring Boot 的 Spring Web MVC的应用中,需要我们引入来启用Web安全
在基于Spring Boot 的 Spring Web MVC的应用中,不需要我们再次引入该注解,spring boot自动配置机制WebSecurityEabalerConfiguration已经引入了该注解
参考 https://www.baeldung.com/spring-deprecated-websecurityconfigureradapter
自定义认证策略:AuthenticationManagerBuilder,UserDetailsManager或UserDetailsService 认证用户配置
用 UserDetailsManager 或着 UserDetailsService component 来实现用户配置
只要将UserDetailsService和PasswordEncoder配置为Spring bean, 存在于上下文中,Spring security会自动设置为AuthenticationManager实例。
不再需要手动将UserDetailsService和PasswordEncoder设置为AuthenticationManager实例
自定义Security策略:
Spring Security 5.7之前, 使用WebSecurityConfigurerAdapter
Spring Security 5.7之后, WebSecurityConfigurerAdapter被弃用, 推荐使用基于组件的安全配置
使用SecurityFilterChain配置HttpSecurity, 使用WebSecurityCustomizer配置WebSecurity
Configure Http Security: SecurityFilterChain
可以通过自定义 SecurityFilterChain 来配置过滤器链????TODO
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfiguration{ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and().formLogin(); return http.build(); } }
Configure Web Security: WebSecurityCustomizer
1.ignore some paths, like images or scripts,配置一些路径放行规则
2.ignore some api, 配置匿名访问,如实现 接口/hello不经过spring security过滤器链,允许匿名访问
3.add a debug level
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; @Configuration @EnableWebSecurity public class SecurityConfiguration { @Bean public WebSecurityCustomizer webSecurityCustomizer() { // return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2"); boolean securityDebug = true; return web -> web.debug(securityDebug).ignoring().antMatchers("/css/**", "/js/**", "/img/**", "/lib/**", "/favicon.ico").antMatchers("/public/*"); } }