Using spring security to deal with CSRF attacks

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 -->
<!-- Security (Only use CSRF Part) -->

Configure filters

public class Application {

  public static void main(String[] args) {, args);
   * Configure CSRF filter
   * @return {@link org.springframework.boot.web.servlet.FilterRegistrationBean}
  public FilterRegistrationBean<CsrfFilter> csrfFilter() {
    FilterRegistrationBean<CsrfFilter> registration = new FilterRegistrationBean<>();
    registration.setFilter(new CsrfFilter(new HttpSessionCsrfTokenRepository()));
    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

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

Keywords: Java FreeMarker Spring JQuery Session

Added by nac20 on Thu, 05 Dec 2019 06:47:28 +0200