Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing my custom user object in jsp page, using spring 3 security

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?

like image 483
NimChimpsky Avatar asked Oct 18 '11 13:10

NimChimpsky


People also ask

How do you allow a user only access their own data in spring boot?

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 .... }

Which code snippet in Spring Security configures that userPage is accessible by the user?

“/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.

What is SecurityContextHolder getContext () getAuthentication ()?

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.

How do I create an authentication Object in Spring Security?

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.


1 Answers

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

like image 113
NimChimpsky Avatar answered Oct 30 '22 21:10

NimChimpsky