DEV Community

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

Posted on

The most basic security for Spring Boot with Thymeleaf

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:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Create the most basic security config ever

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("username").password("{noop}password").roles("USER").and()
                .withUser("username2").password("{noop}password").roles("USER");
    }
}
Enter fullscreen mode Exit fullscreen mode

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}"/>
Enter fullscreen mode Exit fullscreen mode

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"
        method="post">
        <input class="btn btn-link" 
            type="submit"
            value="Log out" />
        <input type="hidden"
            th:name="${_csrf.parameterName}"
            th:value="${_csrf.token}"/>
    </form>
</div>
Enter fullscreen mode Exit fullscreen mode

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:

@GetMapping
public String homePage(Principal principal, Model model) {
    String username = principal.getName();
    model.addAttribute("username", username);
    return "index";
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (4)

Collapse
 
sodiumchl profile image
Lith

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

Collapse
 
brunodrugowick profile image
Bruno Drugowick

Thank you!

I was not planning to do that, but, who knows! Ping me this weekend and we can work on something if you want. And thanks for the suggestions!

Also, although I don't have a proper blog post, I do have some commits that may help you.

For (1), pagination, take a look at this commit, it even has a lengthy explanation: github.com/brunodrugowick/algafood...

For (2), a confirmation before deleting, take a look at the history of commits on this file. There's a confirmation Bootstrap modal integrated with Thymeleaf to ask for confirmation before deleting: github.com/brunodrugowick/three-hu...

Collapse
 
brunodrugowick profile image
Bruno Drugowick

Ops, now I noticed that you meant sort and pagination also for the frontend.

Yeah, for this there's Bootstrap-table (for simple projects, of course). The project from the second link I sent you uses it. It's quite simple, probably you can find something there if you want.

Since it's in portuguese and I have no idea of you speak/read it, again, ping me on the weekend and I can help.

See ya!

Thread Thread
 
sodiumchl profile image
Lith

Thanks so much for the tips. I tried, but still have a few issues that I cannot figure out. Hope you can help.

  1. The Edit modal box is brought up when the Edit button is clicked the first time. After that, the Edit button is no longer responding.
  2. If I use v-on:submit.prevent="postUser" the modal box does not close when Save is clicked. (v-on:submit="postUser" works.)
  3. The nav-bar always has Home highlighted. When the Users page is displayed, Users should be highlighted.

Here is my current html: jsfiddle.net/otu5nrvb