D
D
Danil2021-11-19 05:22:43
Spring
Danil, 2021-11-19 05:22:43

URL to the user's personal account?

Stack:
Spring boot + srping security + thymeleaf
+
postgresql this address is /profile/{id}(id=${user.id}) , but I can’t figure out how to pass the id of the current user to
the header to pull out the id
Spring I study myself, and not so long ago, please help me.

The structure of the
61970a56da582122099959.png
html project:
61970a6fc4880274066135.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Erik Mironov, 2021-11-19
@Danicimo

Spring Security provides the SecurityContextHolder class which allows you to search for the current authenticated user via:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

Authentication provides the following methods:
- Get the username of the logged in user: getPrincipal()
- Get the password of the authenticated user: getCredentials()
- Get the assigned roles of the authenticated user: getAuthorities()
- Get additional information about the authenticated user: getDetails()
You can add to the Model the currently logged in user in your controller:
public String foo(Model model) {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username = user.getUsername();
    model.addAttribute("username", username);
    return "your_view";
}

and then in your html:
<td th:each="user : ${user}">
    <a th:if="${username == user.username}" th:href="@{/profile/{id}(id=${user.id}}">Profile</a>
</td>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question