1. 配置SecurityFilterChain
在Spring Boot应用程序中,通常通过配置类来定义SecurityFilterChain
。Spring Boot 2.x及更高版本与Spring Security 5.x紧密集成,提供了简化的配置方式。以下是一个基于Java配置的例子:
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 SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// 配置哪些请求需要认证
.authorizeRequests()
.antMatchers("/public/**").permitAll() // 公开路径不需要认证
.anyRequest().authenticated() // 其他路径都需要认证