锱铢必较:在spring boot中使用spring security的filter防止CSRF攻击

在一个spring boot项目中,需要防止CSRF攻击,按理说应该集成spring security才对。
但是不想使工程变得太复杂,这时可以只把spring security中的相关filter引入来进行。

在pom中添加相关依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <!-- Security (used for CSRF protection only) -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
    </dependencies>

在app启动时,添加CsrfFilter

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {

    @Bean
    public FilterRegistrationBean csrfFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new CsrfFilter(new HttpSessionCsrfTokenRepository()));
        registration.addUrlPatterns("/*");
        return registration;
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

form中添加CSRF的hidden字段

<input name="${(_csrf.parameterName)!}" value="${(_csrf.token)!}" type="hidden">

ajax中添加CSRF的头

xhr.setRequestHeader("${_csrf.headerName}", "${_csrf.token}");

demo地址是https://github.com/kabike/spring-boot-csrf

标签

发表评论