如何在所有模板中显示当前登录用户的信息,包括在Spring安全应用程序中由WebMvcConfigurerAdapter管理的视图 [英] How to display current logged-in user's information in all templates including view managed by WebMvcConfigurerAdapter in Spring Security application

查看:0
本文介绍了如何在所有模板中显示当前登录用户的信息,包括在Spring安全应用程序中由WebMvcConfigurerAdapter管理的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring Boot应用程序,它使用了Spring Security和Thymeleaf模板。当控制器由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;
    }
    ...
}

在我的模板中,我尝试使用如下代码

<div sec:authentication="firstName"></div> 

但它没有起作用。

我知道可以按如下方式使用ControllerAdvise:

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

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

<span th:text ="${currentUser.getUser().getFirstName()}"></span>

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

那么,有人能告诉我一种自动将登录的用户详细信息插入到我的视图中的方法吗,例如本例中的一些-Logging-in-Page.html?谢谢

推荐答案

由于Balaji Krishnan的提示,实现这一点非常容易。

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

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

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

<span th:text ="${#authentication.getPrincipal().getUser().getFirstName()}"></span>

这篇关于如何在所有模板中显示当前登录用户的信息,包括在Spring安全应用程序中由WebMvcConfigurerAdapter管理的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆