Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf with Spring Security - how to check if user is logged in or not?

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();     } } 
like image 988
tomdavies Avatar asked Mar 06 '15 17:03

tomdavies


People also ask

What is SecurityContextHolder getContext () getAuthentication ()?

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.


2 Answers

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()"> 
like image 93
gregdim Avatar answered Oct 18 '22 19:10

gregdim


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.

like image 45
user1918578 Avatar answered Oct 18 '22 20:10

user1918578