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.
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(); } }
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
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()">
also you can use:
<ul> <li sec:authorize="isAnonymous()"><a class="nav-link" href="/login">Login</a></li> <li sec:authorize="isAuthenticated()"><a class="nav-link" href="/logout">Logout</a></li> <li sec:authorize="isAuthenticated()">Wellcome, <span sec:authentication="name"></span></li> </ul>
to get de current loged user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With