Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:


1. Introduction

Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS and plaintext. For an intro to Thymeleaf and Spring, look at this write-up.

In this article, we will discuss how to prevent Cross-Site Request Forgery (CSRF) attacks in Spring MVC with the Thymeleaf application. Specifically, we will test the CSRF attack for the HTTP POST method.

CSRF is an attack which forces an end user to execute unwanted actions in a web application which is currently authenticated.

2. Maven Dependencies

First, let us see the configurations required to integrate Thymeleaf with Spring. The thymeleaf-spring library is required in our dependencies:


Note that, for a Spring 4 project, the thymeleaf-spring4 library must be used instead of thymeleaf-spring5. The latest version of the dependencies may be found here.

Moreover, to use Spring Security, we need to add the following dependencies:


The latest versions of two Spring Security-related libraries are available here and here.

3. Java Configuration

In addition to the Thymeleaf configuration covered here, we need to add configuration for Spring Security. To do that, we need to create the class:

@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebMVCSecurity {

    public InMemoryUserDetailsManager userDetailsService() {
        UserDetails user = User.withUsername("user1")

        return new InMemoryUserDetailsManager(user);

    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

For more details and description of Security configuration, we refer to the Security with Spring series.

CSRF protection is enabled by default with Java configuration. To disable this helpful feature, we need to add this in configure(…) method:


In XML configuration, we need to specify the CSRF protection manually; otherwise, it will not work:

    <security:csrf />
    <!-- Remaining configuration ... -->

Please also note that if we are using a login or a logout page with a form that has any of PATCH, POST, PUT, or DELETE HTTP verbs, we need to always include the CSRF token as a hidden parameter manually in the code.

Example of using csrf token in a login form:

<form name="login" th:action="@{/login}" method="post"> 
<input type="hidden" 
th:value="${_csrf.token}" />

For the remaining forms, a CSRF token will be automatically added to forms with hidden input if you are using th:action:

  value="32e9ae18-76b9-4330-a8b6-08721283d048" /> 
<!-- Example token -->

4. Views Configuration

Let’s proceed to the main part of HTML files with form actions and testing procedure creation. In the first view, we try to add new students to the list:

<!DOCTYPE html>
<html xmlns=""
<title>Add Student</title>
    <h1>Add Student</h1>
        <form action="#" th:action="@{/saveStudent}" th:object="${student}"
                <li th:errors="*{id}" />
                <li th:errors="*{name}" />
                <li th:errors="*{gender}" />
                <li th:errors="*{percentage}" />
    <!-- Remaining part of HTML -->

In this view, we add a student to the list by providing id, name, gender and percentage (optionally, as stated in the form validation). Before we can execute this form, we need to provide a user and password to authenticate us in a web application.

4.1. Browser CSRF Attack Testing

Now we proceed to the second HTML view. The purpose of it is to try to do a CSRF attack:

<!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<form action="http://localhost:8080/spring-thymeleaf/saveStudent" method="post">
    <input type="hidden" name="payload" value="CSRF attack!"/>
    <input type="submit" />

We know that the action URL is http://localhost:8080/spring-thymeleaf/saveStudent. The hacker wants to access this page to perform an attack.

To test, open the HTML file in another browser without logging in to the application. When you try to submit the form, we will receive the page:


Our request was denied because we sent a request without a CSRF token.

Please note that an HTTP session is used to store CSRF tokens. When the request is sent, Spring compares the generated token with the token stored in the session to confirm that the user is not hacked.

4.2. JUnit CSRF Attack Testing

If you don’t want to test the CSRF attack using a browser, you can also do it via a quick integration test; let’s start with the Spring config for that test:

@ContextConfiguration(classes = { 
  WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
public class CsrfEnabledIntegrationTest {

    // configuration


And move on to the actual tests:

public void addStudentWithoutCSRF() throws Exception {
      .param("id", "1234567").param("name", "Joe").param("gender", "M")

public void addStudentWithCSRF() throws Exception {
      .param("id", "1234567").param("name", "Joe").param("gender", "M")

The first test will result in a forbidden status due to the missing CSRF token, whereas the second will be executed properly.

5. Conclusion

In this article, we discussed how to prevent CSRF attacks using Spring Security and Thymeleaf framework.

The full implementation of this tutorial can be found in the GitHub project.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

res – Security (video) (cat=Security/Spring Security)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.