Search code examples
spring-bootspring-securitythymeleaf

sec:authentication is not working in Spring Boot Security


I have a problem about showing not showing authenticated user full name.

I cannot see any values defined in sec:authentication.

Even through I defined sprng security and embedded it into my html code with supporting thymeleaf, the code didn't work.

How can I fix it?

Here is my CustomerUserDetails class

public class CustomerUserDetails implements UserDetails{

public String getFullName() {
        
        LOGGER.info("CustomerUserDetails | getFullName: " + customer.getFirstName() + " " + customer.getLastName());
        
        return customer.getFirstName() + " " + customer.getLastName();
    }


}

Here is the dependencies shown below.

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>

Here is my code shown below.

I only show this code shown below to show authenticated user full name

<a class="nav-link" th:href="@{/account_details}" ><b>[[${#request.userPrincipal.principal.fullName}]]</b></a>

Why doesn't sec:authentication work?

How can I fix the issue?


Solution

  • Can you show what didn't work?

    Try something like:

    <a class="nav-link" th:href="@{/account_details}"><b sec:authentication="name"/></a>
    

    to verify that you have access to the Authentication instance. Then try:

    <a class="nav-link" th:href="@{/account_details}"><b sec:authentication="details"/></a>
    

    and

    <a class="nav-link" th:href="@{/account_details}"><b sec:authentication="details.fullName"/></a>
    

    to verify your functionality.