首页 > 解决方案 > 使用spring security在jsp中显示用户详细信息

问题描述

我已经在 spring boot 中实现了一个带有 spring security 的应用程序。我需要在成功登录后在jsp页面中显示用户的名字,姓氏和图像路径(用于标题,这意味着即使我们导航到另一个URL也全局可用) 。我正在remember-me使用PersistentLogin. 所以我不能使用会话来存储详细信息。因为如果我关闭浏览器,会话将被破坏。

我已经实现CustomUserDetailsService了,它返回org.springframework.security.core.userdetails.User

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
    //codes
    return new org.springframework.security.core.userdetails.User(
        username,
        password,
        enabled,
        accountNonExpired,
        credentialsNonExpired,
        accountNonLocked,
        authorities);
}

我知道有两个限制

  • 如果我不使用记住我,我可以轻松地在会话中存储。
  • 如果我返回User模型类,我可以使用 jsp 中 的标记CustomUserDetailsService ...轻松获取 jsp 页面中的用户详细信息。<security:authentication property="principal.firstName">但我需要回来org.springframework.security.core.userdetails.User

不幸的是,我需要这两个限制。我的User模特班有firstName, lastName, imagePath,.. etc.

如何在 jsp 页面中显示用户详细信息?有什么可用的方法吗?提前致谢。

标签: springspring-mvcjspspring-bootspring-security

解决方案


Spring 内置提供了相同的解决方案。

Java代码:

public User getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            Object principal = auth.getPrincipal();
            if (principal instanceof User) {
                return ((User) principal);
            }
        }

    }

JSP代码:

${pageContext["request"].userPrincipal.principal}

推荐阅读