Spring security防止CSRF攻击

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

在pom中添加相关依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-freemarkerartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.securitygroupId>
            <artifactId>spring-security-webartifactId>
        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的hidden字段

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

ajax中添加CSRF的头

beforeSend:function (xhr,settings) {
                xhr.setRequestHeader("${_csrf.headerName}", "${_csrf.token}");
            },

转自:https://www.jianshu.com/p/3b8b92657ce9

你可能感兴趣的:(javaweb)