首页 > 解决方案 > 无法在 Spring Boot 2/Thymeleaf 3 中显示登录用户

问题描述

我一直在使用 Spring Boot 2 和 Thymeleaf 3 实现一个基本应用程序。我已经完成了登录/注销工作,安全层要求在特定页面上登录。

我正在将一个非常基本的前端放在一起,并且我正在努力让登录用户的用户名显示出来。

我对这个特定部分的片段是:

    <span class="user" sec:authorize="isAuthenticated()">
        <div sec:authentication="name"></div>
        <a th:href="@{/logout}">Logout</a>
    </span>

无论场景如何,我都会获得“注销”链接,这似乎是由于对象中的anonymousUser设置。authenticated=trueAuthentication

在请求点登录时,我的 Principle 对象看起来像......

principal = {UsernamePasswordAuthenticationToken@10464} "org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ffff4ca0: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: admin; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: admin"
 principal = {User@11314} "org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: admin"
  password = null
  username = "admin"
  authorities = {Collections$UnmodifiableSet@11320}  size = 1
  accountNonExpired = true
  accountNonLocked = true
  credentialsNonExpired = true
  enabled = true
 credentials = null
 authorities = {Collections$UnmodifiableRandomAccessList@11315}  size = 1
 details = {WebAuthenticationDetails@11316} "org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null"
 authenticated = true

name价值不起作用的明显原因是什么?我也尝试过username, principle.username, 并且user只是基于我实际研究和尝试的内容,但我仍然只是在 DOM 中得到了这个:

在此处输入图像描述

任何帮助,将不胜感激。

我有thymeleaf-extras-springsecurity4我的依赖项和xmlns:sec="http://www.thymeleaf.org/extras/spring-security"我的模板<html>标签

标签: javaspringspring-bootthymeleaf

解决方案


推荐阅读