springboot项目防止CSRF攻击

一、在pom中引入spring-security包

<!-- Security -->
<dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-web</artifactId>
</dependency>

 

二、在app启动时,添加CsrfFilter拦截

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {

    @Bean
    public FilterRegistrationBean csrfFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new CsrfFilter(new HttpSessionCsrfTokenRepository()));
        registration.addUrlPatterns("/search");//指定拦截路由,*表示全部拦截
     //registration.addUrlPatterns("/*");
        return registration;
    }

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

 

 

三、form表单提交增加隐藏字段

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

 

四、ajax请求时填加CSRF的头

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

 

posted @ 2021-11-03 16:16  IT民工郑小江  阅读(2193)  评论(0编辑  收藏  举报