Spring boot + thymeleaf: get logged in user
11,506
If you are using spring security and thymeleaf, you could check:
https://github.com/thymeleaf/thymeleaf-extras-springsecurity3
For example:
<div sec:authentication="name">
The value of the "name" property of the authentication object should appear here.
</div>
<div sec:authorize="hasRole('ROLE_ADMIN')">
This content is only shown to administrators.
</div>
Comments
-
Alex Tbk almost 2 years
I would like to know, how I can get the User object from Thymeleaf. Currently I am calling my userService, which will get the user from the DB. I don't like this approach, because for every call a db query will be made.
Is it possible to get the user from memory?
<link href="/css/style2.css" th:if="${@commanderService.getCurrentCommander()} and ${@commanderService.getCurrentCommander().settings == 'template=1'}" rel="stylesheet" type="text/css" />
CommanderService:
public Commander getCurrentCommander() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Commander commander = findByName((String)principal); return commander; }
-
Alex Tbk over 9 years<div sec:authentication="name"></div> will give you only the name of the SecurityObject - what i need is an other field from the User Object
-
Leandro Carracedo over 9 yearsI understand @AlexTbk, if you need the complete User Object one option is to add it to the model or you could also access it like you showed. If you need to define if some stylesheet is added for certain type of users, maybe roles could help.
-
Alex Tbk over 9 yearsThats a good idea - i could set a special role for that stylesheet. Thats it, thanks!