问题
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.
Best regards.
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();
}
}
回答1:
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()">
回答2:
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.
回答3:
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>
来源:https://stackoverflow.com/questions/28904176/thymeleaf-with-spring-security-how-to-check-if-user-is-logged-in-or-not