我是Spring MVC和Spring Security的新手。我已经使用Spring安全性和MVC执行了登录和注册功能。我找不到任何 session 管理方法。
我想访问所有页面上的一些用户详细信息,例如(电子邮件,姓名,ID,角色等)。
我想将它们保存到 session 对象,以便可以在任何页面上获取它们。
我在 Spring 有以下方式参加 session
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
auth.getPrincipal();
但是从由此返回的对象中,我只能获得用户名和密码的详细信息。
但是我需要访问该用户的更多详细信息。
请帮助我获得解决方案。
提前致谢。
我想从SecurityContextHolder.getContext()。getAuthentication()。getDetails();返回我的模型类对象。为此,我需要配置。
问候,
普拉纳夫
最佳答案
您需要使您的模型类实现UserDetails接口(interface)
class MyUserModel implements UserDetails {
//All fields and setter/getters
//All interface methods implementation
}
然后,在您的spring Controller 中,您可以执行以下操作:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object myUser = (auth != null) ? auth.getPrincipal() : null;
if (myUser instanceof MyUserModel) {
MyUserModel user = (MyUserModel) myUser;
//get details from model object
}