简体   繁体   English

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

[英]How to display current logged-in user's information in all templates including view managed by WebMvcConfigurerAdapter in Spring Security application

I have a Spring Boot application that uses Spring Security and Thymeleaf template.我有一个 Spring Boot 应用程序,它使用 Spring Security 和 Thymeleaf 模板。 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.当 controller 由 WebConfigurerAdapter 的子类管理时,我试图在模板中显示登录用户的名字和姓氏。

So, say my WebConfigurerAdapter subclass looks like this所以,假设我的 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");

    }
    ....
}

My User entity class looks like this我的用户实体 class 看起来像这样

@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> 

But it didn't work.但它没有用。

I know it is possible to use a ControllerAdvise as follows:我知道可以按如下方式使用 ControllerAdvise:

@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>

But this doesn't work with any view controller registered with my class MvcConfig.但这不适用于在我的 class MvcConfig 中注册的任何视图 controller。 Rather I will need to make sure each of my controllers are separate classes.相反,我需要确保我的每个控制器都是单独的类。

So, could someone kindly point me to a way to automatically insert the logged-in user details to my view, eg some-logged-in-page.html in this example?那么,有人可以告诉我一种自动将登录用户详细信息插入到我的视图中的方法,例如本例中的 some-logged-in-page.html 吗? Thanks谢谢

It's quite easy to accomplish this, thanks to a hint from Balaji Krishnan.多亏了 Balaji Krishnan 的提示,这很容易实现。

Basically, I had to add the Thymeleaf Spring Security integration module to my build.gradle file as follows:基本上,我必须将 Thymeleaf Spring Security 集成模块添加到我的 build.gradle 文件中,如下所示:

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 4 和 Thymeleaf 3 时:

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

When using Spring boot 2.2.1.使用 Spring Boot 2.2.1 时。

For the maven, Add these lines to the pom.xml对于 maven,将这些行添加到 pom.xml

<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> </dependency>

In the thymeleaf在百里香叶

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

This construct is working for me (spring boot 1.5 and 2.0/thymeleaf 3):这个构造对我有用(spring boot 1.5 和 2.0/thymeleaf 3):
It is documented here (bottom of the page) Thymeleaf + Spring Security integration basics它记录在此处(页面底部) Thymeleaf + Spring Security 集成基础知识

Logged user: <span sec:authentication="name">Bob</span>

Don´t forget to include the sec tag in the html section of your view:不要忘记在视图的 html 部分包含 sec 标记:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
</head>
<body>

I hope this helps!我希望这有帮助!
Have a nice day!祝你今天过得愉快!
Thomas托马斯

As @B378 said, When using Spring Security 4 and Thymeleaf 3: you have to use following.正如@B378 所说,使用 Spring Security 4 和 Thymeleaf 3 时:您必须使用以下内容。

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

Because spring security uses UserDetails internally.因为 spring security 在内部使用 UserDetails。 And UserDetails contains one function called getUsername(). UserDetails 包含一个名为 getUsername() 的函数。

For me, When using Spring boot 2.1.2 I need to use the following对我来说,使用 Spring boot 2.1.2 时,我需要使用以下内容

<span th:text="${#authentication.getPrincipal()}"></span> <!-- No ".getUsername()"-->

With thymeleaf-extras-springsecurity5使用 thymeleaf-extras-springsecurity5

This page was useful.这个页面很有用。 Thanks for all the replies.感谢所有的答复。 Please note that if you are using the latest Spring Boot ie version 2.1.0 then you need to use the following: thymeleaf-extras-springsecurity5请注意,如果您使用的是最新的 Spring Boot 即版本2.1.0那么您需要使用以下内容: thymeleaf-extras-springsecurity5

LINK 关联

For thymleaf 4 and above you have to modify some classes in order to get the info.对于 thymleaf 4 及更高版本,您必须修改一些类才能获取信息。 Heres how you can do that:以下是您如何做到这一点:

First, add the getter of your user getUser(){return this.user;} in the UserDetails class and then push that object in the UserDetailsService object.首先,在 UserDetails 类中添加用户getUser(){return this.user;}的 getter,然后将该对象推getUser(){return this.user;} UserDetailsS​​ervice 对象中。 Without these changes, thymleaf will not parse your HTML file.如果没有这些更改,thymleaf 将不会解析您的 HTML 文件。

Then you can get the info as follows:然后你可以得到如下信息:

<span sec:authentication="principal.user.name">

Don't forget to check if a user is authenticated before trying to print his detais在尝试打印他的详细信息之前,不要忘记检查用户是否经过身份验证

<th:block th:if="${#authorization.expression('isAuthenticated()')}">
                    <span>Hello</span>
                    <span th:text="${#authentication.getPrincipal().getFullName()}"></span>
                </th:block>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM