Status of CSRF vulnerabilities
CSRF (Cross Site Request Forgery) cross site request forgery, also known as One Click Attack or Session Riding, usually abbreviated as CSRF or XSRF, is a malicious use of the website. Although it sounds like cross site scripting (XSS), it is very different from XSS. XSS utilizes trusted users within the site, while CSRF utilizes trusted websites by pretending to be the requests of trusted users. Compared with XSS attacks, CSRF attacks are often less popular (so the resources to prevent them are also very scarce) and difficult to prevent, so they are considered more dangerous than XSS.
CSRF is a confusing attack that relies on web browser.
POM dependence
<!-- template engine freemarker --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!-- Security (Only use CSRF Part) --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> </dependency>
Configure filters
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } /** * Configure CSRF filter * * @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; } }
Add hidden field of CSRF in form request
<input name="${(_csrf.parameterName)!}" value="${(_csrf.token)!}" type="hidden" />
Add header header in AJAX request
xhr.setRequestHeader("${_csrf.headerName}", "${_csrf.token}");
Ajax global configuration of jQuery
jQuery.ajaxSetup({ "beforeSend": function (request) { request.setRequestHeader("${_csrf.headerName}", "${_csrf.token}"); } });