Thymeleaf 无法显示用户的用户名和角色

Thymeleaf can't display username and role of user

我无法在我的索引页上显示经过身份验证的用户的角色和用户名。我正在使用百里香叶。所有角色用户都保存在内存中。我正在使用 spring+mvc

编写和网络应用程序

我在 pom.xml

中添加依赖项
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>

这是我的索引页:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <title>Submission result</title>
<link rel="stylesheet"
     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <h1>login ok: welcome </h1>

  <hr>
<p>
<div sec:authorize="hasRole('ROLE_USER')"> 
    User: <sec:authentication property="principal.username" />
    <br><br>
    Role(s): <sec:authentication property="principal.authorities" />
    </div>
</p>

我也用你的:

<div sec:authorize="hasRole('_USER')"> or is.Authorized(), but I dont diplay nothin.

这是我的安全配置 class:

 public void configure(AuthenticationManagerBuilder auth) throws Exception{

    @SuppressWarnings("deprecation")
    UserBuilder user=User.withDefaultPasswordEncoder();
    auth.inMemoryAuthentication().withUser(user.username("user").password("user").roles("USER"))
    .withUser(user.username("try").password("try").roles("MANAGER", "USER"))
    .withUser(user.username("admin").password("admin").roles("USER", "MANAGER", "ADMIN"));
    
    
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated()
    .and()
    .formLogin()
    .loginPage("/login/log").loginProcessingUrl("/login/control/").permitAll()
    .failureUrl("/client/add")//.permitAll()
    .and()
    .logout().permitAll();

我也在stackoverlofw上看了很多问题,但我没有找到解决办法。我还阅读了 Thymeleaf 官方网站上的指南。

为什么我无法显示:“角色:用户”、“用户名:用户”?

在日志中我没有错误或警告,并且登录工作正常。

我找到了这段代码:th:inline="text">欢迎使用 [[${#httpServletRequest.remoteUser}]] 用于显示用户名,但我不知道这种注解。

示例中的HTML无效(<sec:authentication property="principal.authorities" />)。

我相信您正在寻找的语法是:

User: <span sec:authentication="name"></span>
Role(s): <span sec:authentication="principal.authorities"></span>

Thymeleaf 中对此进行了描述,具有 Spring 安全性 documentation