【问题标题】:Display all user informations with Spring Boot使用 Spring Boot 显示所有用户信息
【发布时间】:2021-02-01 19:25:40
【问题描述】:

我正在使用 Spring Boot 创建一个程序,我想显示所有用户信息(我添加了名字、姓氏、城市等)我可以通过以下方式显示用户名:

<span sec:authentication="principal.username">

现在我想这样显示名字:

<span sec:authentication="principal.FirstName">

这是代码片段:

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
    User user = userRepository.findByEmail(username);
        
    if (user == null) {
        throw new UsernameNotFoundException("invalid username or password.");
    }
        
    return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), mapRolesToAuthorities(user.getRoles()));
}

问题是我想添加什么才能显示所有信息?

【问题讨论】:

    标签: java html spring-boot spring-security


    【解决方案1】:

    如果您想要/需要使用the-authentication-tag

    此标记允许访问存储在安全上下文中的当前身份验证对象。它直接在 JSP 中呈现对象的属性。因此,例如,if Authentication 的 principal 属性是 Spring Security 的 UserDetails 对象的实例,then 使用 将呈现当前用户的名称。

    那么你应该:

    1. 子类org.springframework.security.core.userdetails.User/实现UserDetails。 (MyUserDetails)。
    2. 丰富MyUserDetails(与firstNamelastName等)
    3. 并返回MyUserDetails 而不是new org.springframework.security.core.userdetails.User(...)
    4. 然后您可以访问任何(自定义)属性,例如 &lt;span sec:authentication="principal.firstName"&gt; (principal.foo, principal.bar)

    如果适用的话,更棘手、更贪婪/更高效:

    备用MyUserDetails 部分,让您的(持久,com.my.company...User 扩展 org.springframework.security.core.userdetails.User ...直接返回它(从数据库)。

    但正如文档中所说/人们更喜欢的那样:

    当然,这种事情没有必要使用 JSP 标签,有些人更喜欢在视图中保留尽可能少的逻辑。 您可以访问 MVC 控制器中的 Authentication 对象(通过调用 SecurityContextHolder.getContext().getAuthentication())并将数据直接添加到模型中以供视图呈现。

    (以任何可以想象的方式)

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2019-01-01
      • 2020-07-17
      • 2021-06-03
      相关资源
      最近更新 更多