Two ways to implement SpringBoot project to get information of Spring Security's current user in Thymeleaf

The first method: use the expansion pack to obtain user information

Instructions

1. First introduce the extension dependencies of Thymeleaf and SpringSecurity:

My SpringBoot version is 2.2.6.RELEASEthe default version of SpringSecurity, 5.2.2.RELEASE
so I chose the 5 version of the extension dependency package

<dependency>
	<groupId>org.thymeleaf.extras</groupId>
	<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

You can also choose the 4 extension dependency package according to your own situation: thymeleaf-extras-springsecurity4

2. Then introduce relevant constraints on the Thymeleaf page:

<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"><!-- Thymeleaf提供的Spring Security标签支持 -->

3. Use

登录名:<span sec:authentication="name"></span>
角色:<span sec:authentication="principal.authorities"></span>
用户名:<span sec:authentication="principal.username"></span>
密码:<span sec:authentication="principal.password"></span>

Of course there are other ways (whispering bb

The first method: use Session to obtain user information

Because I used to think that Spring Security directly jumped to the success page without a custom method. It is impossible to obtain user information in the method,
and then suddenly remembered that since I was calling the method in the Service to query the user, it should be available in the Service class. Save the user information in the session, and then get the information in the session on the page

Code:

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserRepository userRepository;
    @Autowired
    HttpSession session;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user!=null)
        {
            session.setAttribute("USER_INFO",user);
            ...(省略)
        }
        ...(省略)
    }
}

Get at the front desk:

用户名:<span th:text="${session.USER_INFO.username}"></span>

Published 184 original articles · praised 6 · 680,000 views

Guess you like

Origin blog.csdn.net/Piconjo/article/details/105443573