Search code examples
htmlspringbootstrap-4thymeleaf

How to make nav-link appear or not using isAuthenticated() and isAnonymous()?


I'm trying to show only one of two elements. If user is logged in I need to show MyProfile, otherwise MyAccount (when anonymous), but two methods always return true. I tried a lot of solutions but no one can fix this problem.

header.xml

<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"
    xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

<!-- other code -->

   <ul class="navbar-nav ml-auto">
         <li><a class="nav-link" href="#" style="color: black">Shopping Cart</a></li>
         <li sec:authorize="isAnonymous()"><a th:href="@{/login}" class="nav-link" style="color: black"> My Account </a></li>
         <li sec:authorize="isAuthenticated()"><a th:href="@{/myProfile}" class="nav-link" style="color: black"> My Profile </a></li>
        </ul>

SecurityConfig.java

    //other code 
private static final String[] PUBLIC_MATCHERS = { "/css/**", "/js/**", "/images/**", "/", "/myAccount",
                "/forgetPassword", "/newUser", "/login" };

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()./* antMatchers("/**") */antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest()
                    .authenticated();

            http.csrf().disable().cors().disable().formLogin().failureUrl("/login?error").defaultSuccessUrl("/")
                    .loginPage("/login").permitAll().and().logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/?logout")
                    .deleteCookies("remember-me").permitAll().and().rememberMe();
        }

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
        }

pom.xml

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>
  • Edit: (some attempts)

I tried both newer and older version of thymeleaf-extras-springsecurity but it doesn't work. Even if I change from sec:authorize=isAuthenticated() to sec:authorize=!isAuthenticated() the result is always the same.

Another attempt was to remove:

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

and to replace it with:

xmlns:sec="http://www.w3.org/1999/xhtml"

I'll edit the post adding other attempts to fix the problem.

  • Edit 2: (solution) I changed artifactId of the dependecy in pom.xml and everything ok.

    org.thymeleaf.extras thymeleaf-extras-springsecurity5


Solution

  • Changed artifactId of the dependecy in pom.xml and everything ok:

    pom.xml

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