Alex Tbk
Alex Tbk

Reputation: 2104

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;
}

Upvotes: 7

Views: 12084

Answers (1)

Leandro Carracedo
Leandro Carracedo

Reputation: 7345

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>

Upvotes: 3

Related Questions