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

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. He is currently holding a position of a Team Leader at Goyello where he is mainly responsible for building and managing teams of professional developers and testers. He is also responsible for maintaining relations with customers and acquiring new ones, mainly through consultancy. He believes in Agile project management and he is a big fan of technology, especially Java related (but not limited too). He likes sharing knowledge about software development and practices, through his blog (blog.codeleak.pl) and Twitter (@kolorobot) but also on internal and external events like conferences or workshops.

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 *

*


four × = 32

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close