Reputation: 2465
usign Spring Security ,I'm trying to get the user id from my CustomUser instance returned from loadUserByUsername method on my CustomUserDetailsService, like I do to get get the Name (get.Name()) with Authentication. Thanks for any tips!
This is how I get the current name of logged user:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
And this is the CustomUser
public class CustomUser extends User {
private final int userID;
public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities, int userID) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userID = userID;
}
}
And the loadUserByUsername method on my Service
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Usuario u = usuarioDAO.getUsuario(s);
return new CustomUser(u.getLogin(), u.getSenha(), u.isAtivo(), u.isContaNaoExpirada(), u.isContaNaoExpirada(),
u.isCredencialNaoExpirada(), getAuthorities(u.getRegraByRegraId().getId()),u.getId()
);
}
Upvotes: 20
Views: 52712
Reputation: 16644
Authentication authentication = ...
CustomUser customUser = (CustomUser)authentication.getPrincipal();
int userId = customUser.getUserId();
You have to add the getUserId()
getter method if you don't already have it.
Upvotes: 32