CSRF防护

未匹配的标注

Spring Boot 中启用 CSRF 防护

CSRF(跨站请求伪造)是一种常见的安全威胁,Spring Security 提供了内置的 CSRF 防护功能。在 Spring Boot 应用中启用 CSRF 防护有以下几种方式:

  1. 默认启用(推荐)

Spring Security 5.x 默认启用了 CSRF 防护。如果你使用的是默认配置,通常不需要额外操作。

  1. 显式配置

如果需要自定义 CSRF 配置,可以通过以下方式:

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                // 可以在这里配置需要排除CSRF保护的路径
                .ignoringRequestMatchers("/api/public/**")
            )
            // 其他安全配置...
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .permitAll()
            )
            .logout(logout -> logout
                .permitAll()
            );

        return http.build();
    }
}
  1. 禁用 CSRF(不推荐)

如果确实需要禁用 CSRF(例如仅提供无状态 API),可以这样配置:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .csrf(csrf -> csrf.disable())
        // 其他配置...
    return http.build();
}
  1. 表单中使用 CSRF 令牌

在 Thymeleaf 模板中自动包含 CSRF 令牌:

<form method="post" action="/process">
    <!-- Thymeleaf 会自动添加CSRF令牌 -->
    <input type="submit" value="提交"/>
</form>

在 JSP 中:

<form method="post" action="/process">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <input type="submit" value="提交"/>
</form>
  1. 在 REST API 中使用 CSRF

对于 REST API,通常有以下几种方式处理 CSRF:

  1. 使用 Cookie 和 Header 方式(推荐):

    .csrf(csrf -> csrf
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    )

    前端需要从 Cookie 中读取 XSRF-TOKEN 并在请求头中发送 X-XSRF-TOKEN

  2. 对于无状态 API,可以考虑禁用 CSRF 并使用其他认证机制(如 JWT)

注意事项

・默认情况下,CSRF 防护会应用到所有 HTTP 方法(除了 GET、HEAD、TRACE、OPTIONS)

・确保登录表单也受到 CSRF 保护

・在前后端分离应用中,需要正确配置 CSRF 令牌的传递方式

通过以上配置,你的 Spring Boot 应用就能得到有效的 CSRF 防护了。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~