Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot + thymeleaf: get logged in user

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;
}
like image 388
Alex Tbk Avatar asked Dec 02 '14 15:12

Alex Tbk


1 Answers

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>
like image 56
Leandro Carracedo Avatar answered Nov 17 '22 07:11

Leandro Carracedo