Why sec:authentication="name" show all user information?

Viewed 2641

I use Spring Boot, Spring Boot Security, thymeleaf-extras-springsecurity5. I want get information about current user and write:

<div sec:authorize="isAuthenticated()"> 
 Authenticated as <span sec:authentication="name"></span></div>

and get All User information Like that:

Authenticated as User(id=7, firstName=TOGRUL, lastName=Mamedov, patronymic=dddddd, email=master555@gmail.com, phone=+99477777777, password=$2a$11$txs/zdaLq.6eeBHz3uyM0e/R6uzJHs2.UIeIeRrV906y6Ia/hMOE6, enabled=true, secret=MVNSUPKHWTAVLIEQ, country=Azerbaijan, state=Baki, city=Badamdar, gender=Man, addressLine=GANJA, zipCode=2001, birthDay=01-07-2020, passportSeria=AZE, passportNumber=1234567, finCode=1234567, avatar=/resources/images/user-icon.png, mytext=null, active=0, isUsing2FA=false, roles=[Role [name=ROLE_USER][id=5]])

For base authentication I use this project. https://github.com/Baeldung/spring-security-registration

How to fix this error if it is a bug? I think password should't be shown anyway. How get username? How get other information if it possible? It is look like Array or some.property

2 Answers

I see you are using thymeleaf. Try this expression and instead of "getSomeProperty()" call any get method of your user class

${#authentication.getPrincipal().getSomeProperty()}

Thymeleaf Extras for Spring Security page on github explains somewhat more coherently, what sec:authentication tag attribute is supposed to convey - in short, e.g. <div sec:authentication="name"></div> is supposed to have the same meaning as <div th:text="${#authentication.name}"></div>, that is, they will both show the result of calling getName() on the Authentication object, that can be passed to a controller method automatically when using the Spring Security / Spring MVC framework, and inspected there.

Possibly, the OP was using a custom UserDetailsService, constructing his own User object, using some kind of toString() method for the username in the standard User(..) constructor - thus resulting in the above strange display. The User object returned from UserDetailsService seems to also be returned by getPrincipal() method of the Authentication object.

In any case, using ${#authentication} object properties as in the other answer, is a more fine-grained approach to getting all kinds of information for the logged-in user, not just the name (which can be rather ambiguous, as this question testifies)

Related