article/java/spring-security.md
2025-03-21 15:27:15 +08:00

97 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

在Spring Security中`SecurityFilterChain``WebSecurityCustomizer`分别用于不同的配置场景,以下是它们的核心区别和使用场景:
### 1. **SecurityFilterChain**
- **作用**:配置`HttpSecurity`定义请求级别的安全规则如URL访问控制、认证机制、CSRF、CORS等
- **适用场景**
- 需要为特定URL路径设置访问权限`permitAll()``authenticated()`)。
- 配置登录/注销行为、表单登录、OAuth2、JWT等认证机制。
- 启用或禁用安全特性如CSRF保护、Session管理
- **特点**
- 请求会经过完整的Spring Security过滤器链。
- 即使路径设置为`permitAll()`请求仍会被安全过滤器处理如记录日志、CSRF验证等
- **示例**
java
复制
```
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll() // 允许匿名访问
.anyRequest().authenticated() // 其他请求需认证
.and()
.formLogin() // 启用表单登录
.loginPage("/login")
.permitAll();
return http.build();
}
```
------
### 2. **WebSecurityCustomizer**
- **作用**:配置`WebSecurity`**全局忽略**某些路径使其完全绕过Spring Security过滤器链。
- **适用场景**
- 忽略静态资源如CSS、JS、图片或公开API路径。
- 提升性能,避免不必要的安全处理。
- **特点**
- 被忽略的路径不会经过任何安全过滤器。
- 无法在此处配置细粒度的安全规则(如角色权限、认证方式)。
- **示例**
java
复制
```
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.antMatchers("/static/**", "/resources/**"); // 完全绕过安全过滤器
}
```
------
### **关键区别**
| 特性 | SecurityFilterChain | WebSecurityCustomizer |
| :--------------- | :------------------------------------ | :----------------------------------- |
| **配置对象** | `HttpSecurity`(请求级安全) | `WebSecurity`全局Web安全 |
| **请求处理** | 经过安全过滤器链 | 完全绕过安全过滤器链 |
| **适用场景** | 细粒度权限控制、认证机制配置 | 忽略静态资源或无安全需求的路径 |
| **性能影响** | 请求会经过过滤器链(可能有开销) | 无开销,直接跳过安全处理 |
| **配置方法示例** | `.antMatchers("/api/**").permitAll()` | `.ignoring().antMatchers("/css/**")` |
------
### **何时选择?**
- **使用 `SecurityFilterChain`**
- 需要对路径应用安全规则如允许匿名访问但仍需CSRF保护
- 需要配置登录页、OAuth2、权限验证等复杂逻辑。
- **使用 `WebSecurityCustomizer`**
- 静态资源(如`/css/**`, `/js/**`)完全无需安全处理。
- 公开API如健康检查`/actuator/health`)无需任何安全机制。
------
### **最佳实践**
- **优先用 `SecurityFilterChain`**:除非明确需要完全绕过安全,否则用`permitAll()`替代`ignoring()`以确保安全特性如CSRF仍生效。
- **谨慎使用 `ignoring()`**:被忽略的路径可能暴露敏感信息或成为安全漏洞。