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">
    <fieldset>
        <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>
        </div>
        <div class="form-group">
            <div class="col-lg-offset-2 col-lg-10">
                <button type="submit" class="btn btn-default">Send</button>
            </div>
        </div>
    </fieldset>
</form>

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

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 -->
 
</security:http>

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" />
 
</form>

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>

Summary

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.

Resources

 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

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

  1. DavidS says:

    Hi,
    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)!

    David

Leave a Reply


2 × = fourteen



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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close