跨站请求伪造(CRSF,Cross-site request forgery)是在Web渗透中较为常见的漏洞之一,被收入在了OWASP TOP 10的荣耀榜单之中,其中简称就是挟持用户在当前已经登录的web站点中执行非本操作的攻击方法。就比如在钟山计算机端口安全联合漏洞共享平台之中所存在的用户认证url下:https://pv.zsun.org.cn/verification?14c4b06b824ec593239362517f538b29=id,在直接请求的时候发现已经被拦截,但是假设一篇文章中带有一个非常特别的图片或按钮,这些无一例外的都将请求该api,则会实现该站点的用户数据批量删除的情况。
CsrfToken CsrcToken是利用用户的登录状态进行攻击的,而相关记录存储至cookie之中,而CsrfToken的防范思路就是,在每个请求中都进行校验,以防止csrf攻击。具体的实现方法就是与前端相互配合,由系统发放一个csrfToken直,用户携带该CsrfToken由系统完成校验。
在默认的情况下,即Spring security 2.0之后,就会默认开启csrf攻击的防护,我们只需要在前端页面进行相应的配置即可。
myLogin.html 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > This is spring security world!</title > </head > <body > <form action ="myLogin.html" method ="post" > <input type ="hidden" name ="${_csrf.parameterName}" value ="${_csrf.token}" /> <input type ="text" name ="username" placeholder ="user" /> <input type ="password" name ="password" placeholder ="pass" /> <input type ="submit" value ="Login" > <label > <input type ="checkbox" name ="remember-me" /> A login</label > </form > </body > </html >
WebSecurityConfig.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package com.example.demo.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.web.csrf.CookieCsrfTokenRepository;@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure (HttpSecurity httpSecurity) throws Exception { httpSecurity.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .and() .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); } }