Search code examples
javaspring-bootthymeleaf

Hide a button in Spring Boot/Thymeleaf application if not logged in


I'm trying to hide a button in the header of my Spring Boot application in the following way with my markup:

<!-- Is not logged in, so don't show "Log In" -->
<li sec:authorize="!isAuthenticated()">
    <a href="/login" th:href="@{/login}" class="btn-login">Log In</a>
</li>\

Is this not correct? I'm using the Thymeleaf templating engine.


Solution

  • Add Spring Security Dialect in spring boot app for sec attribute to work,

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

    If you have a Spring Security Dialect, then you can try,

    <!-- Show login link only for anonymous users -->
    <div sec:authorize="isAnonymous()">
        <a href="/login" th:href="@{/login}" class="btn-login">Log In</a>
    </div>