【问题标题】:Need to change name used sec:authentication in thymeleaf需要更改名称使用 sec:authentication in thymeleaf
【发布时间】:2016-04-23 12:20:30
【问题描述】:

用于登录的凭据是用户名和密码。我想在首页显示名字

      <span sec:authentication="name">bob</span>

但它只提供登录过程中使用的用户名。怎么做。我正在使用弹簧 mvc。请帮忙

【问题讨论】:

  • name 必须在您的身份验证对象中定义,您可以发布它吗?

标签: java spring-security thymeleaf


【解决方案1】:

您可以从 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中&lt;span th:text="${user} ? ${user.name} : Bob"&gt;Bob&lt;/span&gt;

【讨论】:

    猜你喜欢
    • 2016-05-18
    • 2015-10-14
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多