Search code examples
springspring-securityspring-bootthymeleafdialect

sec:authorize not being evaluated on spring-boot project


In my current spring-boot project, I have one view with this html code:

<div id="navbar" class="collapse navbar-collapse">
  <ul class="nav navbar-nav navbar-right" sec:authorize="isAuthenticated()">
     ...
  </ul>
  <ul class="nav navbar-nav navbar-right" sec:authorize="isAnonymous()">
     ...
  </ul>
</div>

but when I execute the application, apparently the tag sec:authorize isn't being evaluated, since both parts are being displayed.

I configure thymeleaf in my application.properties file this way:

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false

my thymeleaf configuration class is implemented this way:

@Configuration
public class Thymeleaf {
  @Bean
  public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine engine  =  new SpringTemplateEngine();
    final Set<IDialect> dialects = new HashSet<IDialect>();
    dialects.add( new SpringSecurityDialect() );
    engine.setDialects( dialects );

    return engine;
  }
}

anyone can point what i am missing here?


Solution

  • Make sure you add the following dependency for Thymeleaf:

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>2.1.2.RELEASE</version>
        <scope>compile</scope>
    </dependency>
    

    Also make sure to add this to the <html>

    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
    

    I also dont think that Set<IDialect> is necessary (correct me if I'm wrong), You can just write it as:

    Bean
    public SpringTemplateEngine templateEngine() {
       SpringTemplateEngine engine = new SpringTemplateEngine();
       engine.setTemplateResolver(templateResolver());
       engine.addDialect(new SpringSecurityDialect());
       return engine;
    }