I have implemented UserDetailsService
, it returns an instance of MyUser
(which implements UserDetails
)
public MyUser loadUserByUsername(String arg0)
Now I want to access my custom getters/fields on MyUser
in my JSP pages, so far I got this:
${pageContext.request.userPrincipal.name}
But that only allows access to a Principal object. How can I access MyUser
object?
In any @Controller , @RestController annotated bean you can use Principal directly as a method argument. @RequestMapping("/users/{user_id}") public String getUserInfo(@PathVariable("user_id") Long userId, Principal principal){ // test if userId is current principal or principal is an ADMIN .... }
“/userPage” is used by USER Role to access and perform Normal user activities. “/adminPage” is used by ADMIN Role to access and perform Admin user activities. ADMIN role can access “/userPage” URL too.
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
In order to construct and set this Authentication object – we need to use the same approach Spring Security typically uses to build the object on a standard authentication. After setting the Authentication in the context, we'll now be able to check if the current user is authenticated – using securityContext.
its easy in the jsp page I added this :
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
...
<sec:authentication property="principal.firstname" />
Where principal is actually an instance of MyUser, so "firstname" can be any of my custom getters and setters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With