Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

1. Overview

In this quick tutorial, we’ll focus on Spring Security with Thymeleaf. We’re going to create a Spring Boot application where we’ll demonstrate the usage of security dialect.

Our choice for frontend technology is Thymeleaf – a modern, server-side web templating engine, with good integration with Spring MVC framework. For more details, please look at our intro article on it.

Lastly, the Spring Security Dialect is a Thymeleaf extras module which, naturally, helps integrate both of these together.

We’re going to be using the simple project we built in our Spring Boot tutorial article; we also have a Thymeleaf tutorial with Spring, where the standard Thymeleaf configuration can be found.

2. Dependencies

First of all, let’s add the new dependency to our Maven pom.xml:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>

It’s recommended always to use the latest version – which we can get over on Maven Central.

3. Spring Security Configuration

Next, let’s define the configuration for Spring Security.

We also need at least two different users to demonstrate the security dialect usage:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    // [...] 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
          .and()
          .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
    }
    
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

As we can see, in configureGlobal(AuthenticationManagerBuilder auth) we define two users with username and password. We can use these to access our application.

Our users have different roles: ADMIN and USER respectively so that we can present them specific content based on a role.

4. Security Dialect

The Spring Security dialect allows us to conditionally display content based on user roles, permissions or other security expressions. It also gives us access to the Spring Authentication object.

Let’s look at the index page, which contains examples of security dialect:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Welcome to Spring Security Thymeleaf tutorial</title>
    </head>
    <body>
        <h2>Welcome</h2>
        <p>Spring Security Thymeleaf tutorial</p>
        <div sec:authorize="hasRole('USER')">Text visible to user.</div>
        <div sec:authorize="hasRole('ADMIN')">Text visible to admin.</div>
        <div sec:authorize="isAuthenticated()">
            Text visible only to authenticated users.
        </div>
        Authenticated username:
        <div sec:authentication="name"></div>
        Authenticated user roles:
        <div sec:authentication="principal.authorities"></div>
    </body>
</html>

We can see the attributes specific to the Spring Security Dialect: sec:authorize and sec:authentication.

Let’s discuss these, one by one.

4.1. Understanding sec:authorize

Simply put, we use sec:authorize attribute to control displayed content.

For example, if we want to only show content to a user with the role USER – we can do: <div sec:authorize=”hasRole(‘USER’)”>.

And, if we want to broaden the access to all authenticated users we can use the following expression:

<div sec:authorize=”isAuthenticated()”>.

4.2. Understanding sec:authentication

The Spring Security Authentication interface exposes useful methods concerning the authenticated principal or authentication request.

To access an authentication object withing Thymeleaf, we can simply use <div sec:authentication=”name”> or <div sec:authentication=”principal.authorities”>.

The former gives us access to the name of the authenticated user, the later allows us to access roles of the authenticated user.

5. Summary

In this article, we used the Spring Security support in Thymeleaf, in a simple Spring Boot application.

As always, a working version of the code shown in this article is available in our GitHub repository.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE
res – Security (video) (cat=Security/Spring Security)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.