如何在所有模板中显示当前登录用户的信息,包括Spring Security应用程序中由WebMvcConfigurerAdapter管理的视图

我有一个使用Spring Security和Thymeleaf模板的Spring Boot应用程序。 当控制器由WebConfigurerAdapter的子类管理时,我试图在模板中显示登录用户的名字和姓氏。

所以,说我的WebConfigurerAdapter子类看起来像这样

@Configuration public class MvcConfig extends WebMvcConfigurerAdapter{ @Override public void addViewControllers(ViewControllerRegistry registry){ registry.addViewController("/some-logged-in-page").setViewName("some-logged-in-page"); registry.addViewController("/login").setViewName("login"); } .... } 

我的用户实体类看起来像这样

 @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, updatable = false) private Long id; @Column(name="first_name", nullable = false) private String firstName; public String getFirstName() { return firstName; } ... } 

在我的模板中,我尝试使用类似的代码

 

但它没有用。

我知道可以使用ControllerAdvise,如下所示:

 @ControllerAdvice public class CurrentUserControllerAdvice { @ModelAttribute("currentUser") public UserDetails getCurrentUser(Authentication authentication) { return (authentication == null) ? null : (UserDetails) authentication.getPrincipal(); } } 

然后使用以下代码访问模板中的详细信息:

  

但这不适用于在我的MvcConfig类中注册的任何视图控制器。 相反,我需要确保每个控制器都是单独的类。

那么,是否有人可以指出我自动将登录的用户详细信息插入到我的视图中的方法,例如本例中的some-logged-in-page.html? 谢谢

由于Balaji Krishnan的暗示,这很容易实现。

基本上,我必须将Thymeleaf Spring Security集成模块添加到我的build.gradle文件中,如下所示:

 compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity3") 

然后在我的模板中我使用了以下标记:

  

使用Spring Security 4和Thymeleaf 3时:

  

这个结构对我有用(春季靴子1.5和2.0 /百里香叶3):
这里记录(页面底部) Thymeleaf + Spring Security集成基础知识

 Logged user: Bob 

不要忘记在视图的html部分中包含sec标记:

      

我希望这有帮助!
祝你今天愉快!
托马斯

正如@ B378所说,当使用Spring Security 4和Thymeleaf 3时:你必须使用以下内容。

  

因为Spring安全性在内部使用UserDetails。 UserDetails包含一个名为getUsername()的函数。