锱铢必较:在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,学习视频),欢迎加群领取。

转载于:https://blog.51cto.com/14226273/2379587

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值