About Rafal Borowiec

Rafal is an IT specialist with about 8 years of commercial experience, specializing in software testing and quality assurance, software development, project management and team leadership.

CSRF protection in Spring MVC, Thymeleaf, Spring Security application

Cross-Site Request Forgery (CSRF) is an attack which forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated. Preventing CSRF attacks in Spring MVC / Thymeleaf application is fairly easy if you use Spring Security 3.2 and above.

How to test?

To test I created a application with restricted area where I can send a form. The form’s source code:

<form class="form-narrow form-horizontal" method="post" th:action="@{/message}" th:object="${messageForm}" action="http://localhost:8080/message">
        <legend>Send a classified message</legend>
        <div class="form-group" th:classappend="${#fields.hasErrors('payload')}? 'has-error'">
            <label for="payload" class="col-lg-2 control-label">Payload</label>
            <div class="col-lg-10">
                <input type="text" class="form-control" id="payload" placeholder="Payload" th:field="*{payload}" name="payload"/>
                <span class="help-block" th:if="${#fields.hasErrors('payload')}" th:errors="*{payload}">May not be empty</span>
        <div class="form-group">
            <div class="col-lg-offset-2 col-lg-10">
                <button type="submit" class="btn btn-default">Send</button>

Knowing that the action URL was http://localhost:8080/message I created a separate page with a HTTP request referencing that URL (with all parameters):

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

I logged on the application and executed the above code. Of course the server allowed me to execute the request because my application is vulnerable to CSRF attacks. To learn more about testing for CSRF visit this link: Testing for CSRF.

How to secure?

If you are using the XML configuration with Spring Security the CSRF protection must be enabled:

<security:http auto-config="true" disable-url-rewriting="true" use-expressions="true">
    <security:csrf />
    <security:form-login login-page="/signin" authentication-failure-url="/signin?error=1"/>
    <security:logout logout-url="/logout" />
    <security:remember-me services-ref="rememberMeServices" key="remember-me-key"/>
    <!-- Remaining configuration -->

In case of Java configruation – it is enabled by default.

As of version Thymeleaf 2.1, CSRF token will be automatically added into forms with hidden input:

<form class="form-narrow form-horizontal" method="post" action="/message">
    <!-- Fields -->
    <input type="hidden" name="_csrf" value="16e9ae08-76b9-4530-b816-06819983d048" />

Now, when you try to repeat the attack, you will see Access Denied error.

One thing to remember, though, is that enabling CSRF protection ensures that log out requires a CSRF token. I used JavaScript to submit a hidden form:

<a href="/logout" th:href="@{#}" onclick="$('#form').submit();">Logout</a>
<form style="visibility: hidden" id="form" method="post" action="#" th:action="@{/logout}"></form>


In this short article, I showed how easily you can utilize CSRF protection whilst working with Spring MVC (3.1+), Thymeleaf (2.1+) and Spring Security (3.2+). As of Spring Security 4 CSRF will be enabled by default also when XML configuration will be used. Please note, that HTTP session is used in order to store CSRF token. But this can be easily changed. For more details, see references.



Related Whitepaper:

Introduction to Web Applications Development

Kick start your web apps development with this introductory ebook!

This 376 page eBook 'Introduction to Web Applications Development', starts with an introduction to the internet, including a brief history of the TCT/IP protocol and World Wide Web. It defines the basic concepts for web servers and studies the case of Apache, the most used webserver, while other free software webservers are not forgotten. It continues with webpage design focusing on HTML and JavaScript. XML Schemas, their validation and transformation are covered as well as dynamic webpages built with CGI, PHP or JSP and database access.

Get it Now!  

2 Responses to "CSRF protection in Spring MVC, Thymeleaf, Spring Security application"

  1. DavidS says:

    I would highly advise anybody reading this post to test the MVN archetype mentioned at the end.
    Thank you s much for that fantastic job (the MVN archetype)!


Leave a Reply

1 + one =

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books