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

前端 未结 8 1908
眼角桃花
眼角桃花 2020-12-14 13:02

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 t

相关标签:
8条回答
  • 2020-12-14 13:46

    It's quite easy to accomplish this, thanks to a hint from Balaji Krishnan.

    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>
    
    0 讨论(0)
  • When using Spring boot 2.2.1.

    For the maven, Add these lines to the 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>

    0 讨论(0)
  • 2020-12-14 13:53

    For thymleaf 4 and above you have to modify some classes in order to get the info. 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. Without these changes, thymleaf will not parse your HTML file.

    Then you can get the info as follows:

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

    0 讨论(0)
  • 2020-12-14 13:54

    This page was useful. Thanks for all the replies. Please note that if you are using the latest Spring Boot i.e. version 2.1.0 then you need to use the following: thymeleaf-extras-springsecurity5

    LINK

    0 讨论(0)
  • 2020-12-14 14:01

    For me, When using Spring boot 2.1.2 I need to use the following

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

    With thymeleaf-extras-springsecurity5

    0 讨论(0)
  • 2020-12-14 14:04

    When using Spring Security 4 and Thymeleaf 3:

    <span th:text="${#authentication.getPrincipal().getUsername()}"></span>
    
    0 讨论(0)
提交回复
热议问题