Reputation: 8894
I have implemented an app in spring boot with spring security. I need to display User's firstname, lastname and the image path in jsp page (which is used for header, it means globally available even if we navigate to another URL) after successfully logged in. I'm using remember-me
using PersistentLogin
. So I can't use session to store details. Because If I close the browser, session will be destroyed.
I have implemented CustomUserDetailsService
, it returns org.springframework.security.core.userdetails.User
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
//codes
return new org.springframework.security.core.userdetails.User(
username,
password,
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
authorities);
}
I know there are two limitaions
- If I don't use remember-me, I can easily store within session.
- If I return
User
model class inCustomUserDetailsService ...
,I can easily get user details in jsp page using<security:authentication property="principal.firstName">
tag in jsp. But I need to returnorg.springframework.security.core.userdetails.User
Unfortunately I need both limitation. My User
model class has firstName, lastName, imagePath,.. etc.
How can I display user details in jsp page? Any approaches available? Thanks in advance.
Upvotes: 0
Views: 1968
Reputation: 8894
HWat i have done is, I created a prototype of User
called UserAuth
public class UserAuth extends org.springframework.security.core.userdetails.User{
private String firstName;
private String lastName;
private String imagePath;
public UserAuth(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities,
String firstName, String lastName, String imagePath) {
super(username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities);
this.firstName = firstName;
this.lastName = lastName;
this.imagePath = imagePath;
}
//getters and setters
}
In CustomeUserDetailsService
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
//codes
return UserAuth
username,
password,
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
authorities,
user.getFirstName(),
user.getLastName(),
user.getImagePath());
}
Upvotes: 0
Reputation: 15878
Spring inbuilt provides the solution to do the same.
Java code :
public User getCurrentUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof User) {
return ((User) principal);
}
}
}
JSP code :
${pageContext["request"].userPrincipal.principal}
Upvotes: 1