Home » Java » Enterprise Java » CSRF protection in Spring MVC, Thymeleaf, Spring Security application

About Rafal Borowiec

Software developer, Team Leader, Agile practitioner, occasional blogger, lecturer. Open Source enthusiast, quality oriented and open-minded.

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 our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

2 comments

  1. 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

Your email address will not be published. Required fields are marked *

*


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.