两种方法实现SpringBoot项目在Thymeleaf中获取Spring Security当前用户的信息

种方法:使用扩展包获取用户信息

使用方法

1、首先 引入Thymeleaf和SpringSecurity的扩展依赖:

我的SpringBoot版本是2.2.6.RELEASE 其默认引入的的SpringSecurity版本是5.2.2.RELEASE
因此 我选择5版本的扩展依赖包

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

也可根据自己情况选择4的扩展依赖包:thymeleaf-extras-springsecurity4

2、然后 在Thymeleaf页面上引入相关约束:

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

3、使用

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

当然 还有其它方法(小声bb

种方法:使用Session获取用户信息

因为之前一直以为Spring Security是直接跳转到成功页面的 没有经过自定义的方法 无法在方法中获取用户信息
然后突然想起来 我既然是调用Service里的方法查询用户的 那么就应该可以在Service类中将用户信息存到Session中 然后在页面中获取Session里的信息

代码:

@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);
            ...(省略)
        }
        ...(省略)
    }
}

前台获取:

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

发布了184 篇原创文章 · 获赞 6 · 访问量 68万+

猜你喜欢

转载自blog.csdn.net/Piconjo/article/details/105443573