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

前端 未结 8 1909
眼角桃花
眼角桃花 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 14:04

    This construct is working for me (spring boot 1.5 and 2.0/thymeleaf 3):
    It is documented here (bottom of the page) Thymeleaf + Spring Security integration basics

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

    Don´t forget to include the sec tag in the html section of your view:

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

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

    As @B378 said, When using Spring Security 4 and Thymeleaf 3: you have to use following.

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

    Because spring security uses UserDetails internally. And UserDetails contains one function called getUsername().

    0 讨论(0)
提交回复
热议问题