Spring Boot基础功能:CSRF
使用Spring Security防止CSRF跨域攻击。
添加Security依赖
<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>
添加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隐藏字段
<input name="${(_csrf.parameterName)!}" value="${(_csrf.token)!}" type="hidden">
AJAX添加CSRF头
xhr.setRequestHeader("${_csrf.headerName}", "${_csrf.token}");
发表回复