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()
);
}
As of Spring Security version 5.7. 1, the default username is user and the password is randomly generated and displayed in the console (e.g. 8e557245-73e2-4286-969a-ff57fe326336 ).
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.
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.
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