| 知乎专栏 |
return http.authorizeHttpRequests(authorize -> {
try {
authorize
// 放行登录接口
.requestMatchers("/", "/ping").permitAll()
.requestMatchers("/token").permitAll()
// 放行资源目录
.requestMatchers("/static/**", "/resources/**").permitAll()
// 其余的都需要权限校验
.anyRequest().authenticated()
// 防跨站请求伪造
.and().csrf(csrf -> csrf.disable());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
).build();
开启 httpBasic 认证
// 使用@EnableWebSecurity注解开启Spring Security功能
@EnableWebSecurity
public class SecurityConfig {
// 定义一个SecurityFilterChain bean,用于配置安全过滤器链
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// 配置授权请求规则
.authorizeRequests()
// 任何请求都需要认证
.anyRequest()
.authenticated()
// 使用and()方法连接多个配置
.and()
// 开启HTTP基本认证功能
.httpBasic();
return http.build();
}
}