服务器之家

服务器之家 > 正文

使用SpringSecurity处理CSRF攻击的方法步骤

时间:2021-07-19 09:07     来源/作者:BBFBBF

csrf漏洞现状

csrf(cross-site request forgery)跨站请求伪造,也被称为one click attack或者session riding,通常缩写为csrf或xsrf,是一种对网站的恶意利用。尽管听起来像跨站脚本(xss),但它与xss非常不同,xss利用站点内的信任用户,而csrf则通过伪装成受信任用户的请求来利用受信任的网站。与xss攻击相比,csrf攻击往往不大流行(因此对其进行防范的资源也相当稀少)和难以防范,所以被认为比xss更具危险性。

csrf是一种依赖web浏览器的、被混淆过的代理人攻击(deputy attack)。

pom依赖

?
1
2
3
4
5
6
7
8
9
10
<!-- 模板引擎 freemarker -->
<dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-freemarker</artifactid>
</dependency>
<!-- security (只使用csrf部分) -->
<dependency>
 <groupid>org.springframework.security</groupid>
 <artifactid>spring-security-web</artifactid>
</dependency>

配置过滤器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@springbootapplication
public class application {
 
 public static void main(string[] args) {
  springapplication.run(application.class, args);
 }
 
 /**
  * 配置csrf过滤器
  *
  * @return {@link org.springframework.boot.web.servlet.filterregistrationbean}
  */
 @bean
 public filterregistrationbean<csrffilter> csrffilter() {
  filterregistrationbean<csrffilter> registration = new filterregistrationbean<>();
  registration.setfilter(new csrffilter(new httpsessioncsrftokenrepository()));
  registration.addurlpatterns("/*");
  registration.setname("csrffilter");
  return registration;
 }
}

在form请求中添加csrf的隐藏字段

?
1
<input name="${(_csrf.parametername)!}" value="${(_csrf.token)!}" type="hidden" />

在ajax请求中添加header头

?
1
xhr.setrequestheader("${_csrf.headername}", "${_csrf.token}");

jquery的ajax全局配置

?
1
2
3
4
5
jquery.ajaxsetup({
 "beforesend": function (request) {
  request.setrequestheader("${_csrf.headername}", "${_csrf.token}");
 }
});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000018402597

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国 2021-05-08
返回顶部