DEV Community

Cover image for The most basic security for Spring Boot with Thymeleaf

The most basic security for Spring Boot with Thymeleaf

brunodrugowick profile image Bruno Drugowick ・2 min read

I like to develop small proof of concept applications. Although just validating, some security stuff may be necessary sometimes. Most often than not I also want to have 2 or more users...

So if you're using Spring and Thymeleaf, for the most basic and quick setup for a Spring MVC web app, just do:

Add the pom.xml dependency

Just add this to the file:


Create the most basic security config ever

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

Additional stuff

Well, you're mostly done, but there're a few things that I believe are important to consider.

CSRF protection

The first thing is that with the current config you won't be able to make a HTTP POST request because Spring is automatically protecting your app from CSRF attacks. You must add the csrf token already provided by Spring when POSTing.

You do that by adding the following inside your <form> and </form> tags:

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

Logout link

The current configuration provides you a login page that may be enough for demonstrations. But having more than one user makes you want to logout and show some behavior with the other users.

For this, just add the following form somewhere in your app:

<div class="text-light">
    <form action="/logout"
        <input class="btn btn-link" 
            value="Log out" />
        <input type="hidden"

Getting the logged user

Finally, if you want to know which user is logged, inject a Principal instance on your controller methods. Here's an example:

public String homePage(Principal principal, Model model) {
    String username = principal.getName();
    model.addAttribute("username", username);
    return "index";

Now you can show the logged user right on your homepage.

AQAP Series

As Quickly As Possible (AQAP) is a series of quick posts on something I find interesting. I encourage (and take part on) the discussions on the comments to further explore the technology, library or code quickly explained here.

Image by Jason King por Pixabay

Discussion (1)

Editor guide
sodiumchl profile image

This is a GREAT series. Thanks!

It would be great if you could add:
(1) Sorting and pager to the users table
(2) Confirmation for the delete operation