Spring boot + thymeleaf: log in user

I would like to know how I can get a User object from Thymeleaf. I am currently calling my userService, which will get the user from the database. I do not like this approach, because a db request will be executed for each call.

Is it possible to get a 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; } 
+5
source share
1 answer

If you use spring security and thymeleaf, you can check: https://github.com/thymeleaf/thymeleaf-extras-springsecurity3
For instance:

 <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> 
+3
source

Source: https://habr.com/ru/post/1208165/


All Articles