使用SpringSecurity处理CSRF攻击

发布时间:2019-06-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了使用SpringSecurity处理CSRF攻击脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

CSRF漏洞现状

CSRF(Cross-sITe request forgery)跨站请求伪造,也被称为One Click Attack或者Session Riding,通常缩写为CSRFXSRF,是一种对网站的恶意利用。尽管听起来像跨站脚本(XSS),但它与XSS非常不同,XSS利用站点内的信任用户,而CSRF则通过伪装成受信任用户的请求来利用受信任的网站。与XSS攻击相比,CSRF攻击往往不大流行(因此对其进行范的资也相当稀少)和难以防范,所以被认为比XSS更具危险性。
CSRF是一种依赖web浏览器的、被混淆过的代理人攻击(deputy attack)。

POM依赖

<!-- 模板引擎 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>

配置过滤器

@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的隐藏字段

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

AJAX请求中添加header头

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

jQuery的Ajax全局配置

jquery.ajaxSETUP({
  "beforeSend": function (request) {
    request.setRequestHeader("${_csrf.headerName}", "${_csrf.token}");
  }
});

脚本宝典总结

以上是脚本宝典为你收集整理的使用SpringSecurity处理CSRF攻击全部内容,希望文章能够帮你解决使用SpringSecurity处理CSRF攻击所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。