【发布时间】:2016-04-23 12:20:30
【问题描述】:
用于登录的凭据是用户名和密码。我想在首页显示名字
<span sec:authentication="name">bob</span>
但它只提供登录过程中使用的用户名。怎么做。我正在使用弹簧 mvc。请帮忙
【问题讨论】:
-
name 必须在您的身份验证对象中定义,您可以发布它吗?
标签: java spring-security thymeleaf
用于登录的凭据是用户名和密码。我想在首页显示名字
<span sec:authentication="name">bob</span>
但它只提供登录过程中使用的用户名。怎么做。我正在使用弹簧 mvc。请帮忙
【问题讨论】:
标签: java spring-security thymeleaf
您可以从 Spring Security Context 中获取用户并将其转换为您的“用户”模型,然后按照您的喜好对待它。在此示例中,我使用了一个 @ModelAttribute,您可以将其添加到您的控制器或顾问 (@ControllerAdvice) 中
@ModelAttribute("user")
public MyCustomUser getUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getPrincipal())) {
return (MyCustomUser) auth.getPrincipal();
}
return null;
}
然后在你的html中<span th:text="${user} ? ${user.name} : Bob">Bob</span>
【讨论】: