Spring Security 教程(29)、Web应用安全

CSRF 防护的完整方案

Spring Security 配图
Spring Security 配图
Spring Security 配图

CSRF(跨站请求伪造)是 Web 应用最常见的攻击之一。攻击者诱导用户在已认证的浏览器中执行非本意的操作。

Spring Security 默认启用 CSRF 防护,使用 Synchronizer Token 模式:

1
2
3
4
http.csrf(csrf -> csrf
.csrfTokenRepository(CsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers("/api/**")
);

工作原理:服务器生成一个随机的 CSRF Token,存储在 Session 中,同时通过 Cookie 或表单隐藏字段传递给客户端。客户端提交表单时,必须携带相同的 Token。服务器验证 Token 匹配后才处理请求。

XSS 防护

Spring Security 不直接提供 XSS 防护,但可以通过配置安全响应头来缓解:

1
2
3
4
5
6
7
8
9
http.headers(headers -> headers
.contentTypeOptions() // X-Content-Type-Options: nosniff
.frameOptions().deny() // X-Frame-Options: DENY
.xssProtection() // X-XSS-Protection: 1; mode=block
.referrerPolicy(referrer ->
referrer.policy(ReferrerPolicy.SAME_ORIGIN))
.contentSecurityPolicy(csp ->
csp.policyDirectives("default-src 'self'"))
);

CORS 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
http.cors(cors -> cors
.configurationSource(corsConfigurationSource())
);

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}

安全响应头配置

1
2
3
4
5
6
7
8
9
http.headers(headers -> headers
.hsts(header -> header
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
)
.cacheControl() // Cache-Control: no-store
.frameOptions()
.sameOrigin()
);
响应头 作用
X-Content-Type-Options: nosniff 防止 MIME 类型嗅探
X-Frame-Options: DENY 防止点击劫持
X-XSS-Protection: 1; mode=block 启用浏览器 XSS 过滤
Strict-Transport-Security 强制 HTTPS
Content-Security-Policy 限制资源加载来源
Referrer-Policy 控制 Referer 信息泄露

会话安全配置

1
2
3
4
5
6
http.sessionManagement(session -> session
.sessionFixation().migrateSession()
.maximumSessions(1)
.expiredUrl("/login?expired")
.sessionAccessDeniedHandler(new CustomSessionAccessDeniedHandler())
);

安全配置检查清单

web-app-security 配图
web-app-security 配图
web-app-security 配图

  • 启用 CSRF 防护(API 场景评估后决定是否关闭)
  • 配置安全响应头(HSTS、X-Frame-Options、CSP)
  • 启用 HTTPS(生产环境必须)
  • 配置会话超时(建议不超过 30 分钟)
  • 启用会话固定攻击防护
  • 配置并发 Session 限制
  • 对敏感操作进行二次认证
  • 定期审查安全配置和依赖版本