spring - 使用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 页面中显示用户详细信息?有什么可用的方法吗?提前致谢。
解决方案
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}
推荐阅读
- javascript - 如何使用 JavaScript 变量添加背景图片
- time-complexity - 如何解决给定代码块示例的 O-Notation?
- javascript - 为什么当我在本地存储中添加新产品时,他会被新产品替换
- python - Django 表单下拉字段显示其他用户拥有的数据
- angular - Angular Guard 或 Firebase Auth 是否容易被黑客入侵
- python - 如何在 Python 中转义文本以在 Bash 命令中使用?
- php - Laravel 发送邮件 SMTP 邮件
- javascript - 使用传单单击时如何过滤和显示特征的属性?
- eclipse-plugin - Eclipse 插件在 Windows 和 Linux 上加载,但在 MacOS 上不加载
- database - oracle 是否会尝试自动重新运行失败的作业?我在哪里可以看到相同的设置?