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>

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");
    }
}

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

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>

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";
}

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

This post is also available on DEV.