How can I display the current logged in User with Spring Boot Thymeleaf?

后端 未结 4 655
故里飘歌
故里飘歌 2021-01-18 19:18

I am trying to display the details of the current user however I keep getting errors. I tried accessing the authenticated user from the template but that did not work as I w

相关标签:
4条回答
  • 2021-01-18 19:37

    I figured out how to fix my problem.

    I created this method in a controller:

      @Autowired
    UserRepository userR;
    @GetMapping
    public String currentUser(@ModelAttribute("user") @Valid UserRegistrationDto userDto, BindingResult result, Model model) {
    
        Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
        String email = loggedInUser.getName(); 
    
         User user = userR.findByEmailAddress(email);
        String firstname = user.getFirstName();
         model.addAttribute("firstName", firstname);
        model.addAttribute("emailAddress", email);
    
        return "userProfile1"; //this is the name of my template
    }
    

    and then I added this line of code in my html template:

    Email: th:text="${emailAddress}"

    0 讨论(0)
  • 2021-01-18 19:51

    You can use Thymeleaf extras for display authenticated user details.

    Thymeleaf Extras Springsecurity4

        <div th:text="${#authentication.name} ></div>
    
    0 讨论(0)
  • 2021-01-18 19:54

    Reference (4. Spring Security Dialect):

    https://www.thymeleaf.org/doc/articles/springsecurity.html

    Add dependencies pom.xml

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

    and the view (Thymeleaf):

    <div sec:authorize="isAuthenticated()"> 
        Authenticated user roles:
        Logged user: <span sec:authentication="name"></span> |
        Roles: <span sec:authentication="principal.authorities"></span>
    </div>
    

    I hope you serve them

    0 讨论(0)
  • 2021-01-18 20:00

    The problem is here:

    return new 
    org.springframework.security.core.userdetails.User(user.getEmailAddress(),
            user.getPassword(),
            mapRolesToAuthorities(user.getRoles()));
    

    You lose the reference to your User entity. Change it to:

    return user;
    

    For this to work, you need to update your User entity to implement UserDetails interface:

    public class User implements UserDetails {
        // some new methods to implement
    }
    

    Then, your Thymleaf code should work. Another way of getting the firstName would be:

    <span th:text="${#request.userPrincipal.principal.firstName}"></span>
    
    0 讨论(0)
提交回复
热议问题