Thymeleaf with Spring Security - how to check if user is logged in or not?

tomdavies picture tomdavies · Mar 6, 2015 · Viewed 21.3k times · Source

I'm using Spring Boot with Thymeleaf and Spring Security. I've got a simple view with a login link. When the user logs in, I'd like to change login link to logout link.

I tried:

<div sec:authorize="#{isAuthenticated()}">
  <a th:href="@{/logout}">Log out</a>
</div>
<div sec:authorize="#{isAnonymous()}">
  <a th:href="@{/login}">Log in</a>
</div>

but it's not working - it displays both links.

Best regards.

EDIT: I solved it. I had to register Thymeleaf dialect. In order to do this, I created a new config class, that creates SpringSecurityDialect bean:

@Configuration
public class ThymeleafConfig {

    @Bean
    public SpringSecurityDialect springSecurityDialect(){
        return new SpringSecurityDialect();
    }
}

Answer

grid picture grid · Mar 6, 2015

According to thymeleaf docs no spel expression is required. This is not a th: attribute.

So you may try :

<div sec:authorize="isAuthenticated()">

<div sec:authorize="isAnonymous()">