【问题标题】:Get User details from Session in Spring Security从 Spring Security 中的 Session 获取用户详细信息
【发布时间】:2013-07-23 12:22:03
【问题描述】:

我是 Spring MVC 和 Spring Security 的新手。我已经使用 Spring 安全性和 MVC 执行了登录和注册功能。我找不到任何会话管理方法。

我想访问所有页面上的一些用户详细信息,例如(电子邮件、姓名、ID、角色等)。 我想将这些保存到会话对象中,以便可以在任何页面上获取它们。

我在春季的会话中得到以下方式

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
auth.getPrincipal();

但是从这个返回的对象中我只能得到用户名和密码的详细信息。

但我需要访问该用户的更多详细信息。

  • 有没有办法通过将其保存到 session 和 jsp 页面上的 get 来做到这一点?
  • 或者在春季是否有任何 OOTB 方式来完成这项工作?

请帮我解决这个问题。 提前致谢。

我想从 SecurityContextHolder.getContext().getAuthentication().getDetails() 中返回我的模型类对象;为此我需要配置。

问候, 普拉纳夫

【问题讨论】:

  • 如果你有用户名你不能通过用户名查询吗?我假设您用来保存用户信息的表中包含用户名(这是唯一的)。手动或通过 ORM 查询并映射到 User 模型对象。

标签: spring session spring-mvc spring-security


【解决方案1】:

你需要让你的模型类实现UserDetails接口

class MyUserModel implements UserDetails {
    //All fields and setter/getters

    //All interface methods implementation
}

然后在你的 spring 控制器中你可以这样做:

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        
}

【讨论】:

    【解决方案2】:

    您可以使用它来获取UserDetails(或任何带有您的自定义详细信息的实现)。

    UserDetails userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
    

    如果没有可用的,您可以从UserDetailsService 加载用户详细信息。

    在这两种情况下,我认为您必须自己将它们保存在会话范围 bean 中。

    【讨论】:

    • 我想让我的模型类对象从 SecurityContextHolder.getContext().getAuthentication().getDetails();为此我需要配置
    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 2012-05-23
    • 2011-01-30
    • 2016-08-01
    • 2020-08-28
    • 1970-01-01
    • 2023-04-03
    • 2018-03-14
    相关资源
    最近更新 更多