如何在所有模板中显示当前登录用户的信息,包括Spring Security应用程序中由WebMvcConfigurerAdapter管理的视图 [英] How to display current logged-in user's information in all templates including view managed by WebMvcConfigurerAdapter in Spring Security application
问题描述
我有一个使用Spring Security和Thymeleaf模板的Spring Boot应用程序.当控制器由WebConfigurerAdapter的子类管理时,我试图在模板中显示登录用户的名字和姓氏.
I have a Spring Boot application that uses Spring Security and Thymeleaf template. I am trying to display the logged-in user's first name and last name in a template when the controller is managed by a subclass of WebConfigurerAdapter.
所以,说我的WebConfigurerAdapter子类看起来像这样
So, say my WebConfigurerAdapter subclass looks like this
@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;
}
...
}
在我的模板中,我尝试使用
In my template, I have tried using code like
<div sec:authentication="firstName"></div>
但是没有用.
我知道可以如下使用ControllerAdvise:
I know it is possible to use a ControllerAdvise as follows:
@ControllerAdvice
public class CurrentUserControllerAdvice {
@ModelAttribute("currentUser")
public UserDetails getCurrentUser(Authentication authentication) {
return (authentication == null) ? null : (UserDetails) authentication.getPrincipal();
}
}
,然后使用以下代码访问模板中的详细信息:
and then access the details in the template using code like:
<span th:text ="${currentUser.getUser().getFirstName()}"></span>
但是,这不适用于在我的类MvcConfig中注册的任何视图控制器.相反,我需要确保每个控制器都是单独的类.
But this doesn't work with any view controller registered with my class MvcConfig. Rather I will need to make sure each of my controllers are separate classes.
因此,有人可以为我指出一种自动将登录的用户详细信息插入到我的视图中的方法,例如在此示例中,是否有some-logged-in-page.html?谢谢
So, could someone kindly point me to a way to automatically insert the logged-in user details to my view, e.g. some-logged-in-page.html in this example? Thanks
推荐答案
要实现这一点很容易,这要归功于Balaji Krishnan的提示.
It's quite easy to accomplish this, thanks to a hint from Balaji Krishnan.
基本上,我必须将Thymeleaf Spring Security集成模块添加到build.gradle文件中,如下所示:
Basically, I had to add the Thymeleaf Spring Security integration module to my build.gradle file as follows:
compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity3")
然后在我的模板中,我仅使用了以下标记:
Then in my template I just used the following markup:
<span th:text ="${#authentication.getPrincipal().getUser().getFirstName()}"></span>
这篇关于如何在所有模板中显示当前登录用户的信息,包括Spring Security应用程序中由WebMvcConfigurerAdapter管理的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!