alibehzadian wrote:
If you want to get current logged in user, use the code snippet below:
User currentUser = null;
SecurityContext ctx = SecurityContextHolder.getContext();
if (ctx.getAuthentication() != null) {
Authentication auth = ctx.getAuthentication();
if (auth.getPrincipal() instanceof UserDetails) {
currentUser = (User) auth.getPrincipal();
} else if (auth.getDetails() instanceof UserDetails) {
currentUser = (User) auth.getDetails();
} else {
throw new AccessDeniedException("User not properly authenticated.");
}
}
Ali Behzadian Nejad.
as you told that you're using spring then perhaps you can do as same that I do, that I create a class, I put it in src/service/.../util/, I call it UserUtil because I call it often in my application, it return the logged in user, with parameter UserManager that already appfuse had. and this is my full code of that class:
public final class UserUtil {
public synchronized static User getCurrentUser(UserManager mgr) {
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username;
if (obj instanceof UserDetails) {
username = ((UserDetails) obj).getUsername();
} else {
username = obj.toString();
}
return username != null ? mgr.getUserByUsername(username) : null;
}
}
HTH