Reputation: 1976
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();
}
}
Upvotes: 43
Views: 37481
Reputation: 81
Following did not work for me for 3.0.4.RELEASE thymeleaf-extras-springsecurity4:
<div sec:authorize="isAnonymous()">
Instead, following worked:
<div th:if="${#authentication == null}">
Upvotes: 2
Reputation: 91
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.
Upvotes: 4
Reputation: 1316
Can also use sec:authorize="isFullyAuthenticated()"
which checks if its an anonymousUser
and rememberMe
.
<div class="button-group" sec:authorize="!isFullyAuthenticated()">
<a href="/login">Login</a>
<a href="/register">Register</a>
</div>
<div class="button-group" sec:authorize="isFullyAuthenticated()">
<a href="/logout">Logout</a>
</div>
Upvotes: 2
Reputation: 2071
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()">
Upvotes: 46