錙銖必較:在spring boot中使用神器防止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 {br/>@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}");
喜歡的點點關注,點點贊。

對Java技術,架構技術感興趣的同學,歡迎加QQ羣585550789,一起學習,相互討論。

羣內已經有小夥伴將知識體系整理好(源碼,筆記,PPT,學習視頻),歡迎加羣領取。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章