How to get user id from CustomUser in Spring Security

usign Spring Security. I am trying to get the user ID from my CustomUser instance returned by the loadUserByUsername method in my CustomUserDetailsService, the same way I get the Name (get.Name ()) with Authentication. Thanks for any tips!

This is how I get the current registered user name:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String name = authentication.getName(); 

And this is 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 in 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() ); } 
+8
source share
1 answer
 Authentication authentication = ... CustomUser customUser = (CustomUser)authentication.getPrincipal(); int userId = customUser.getUserId(); 

You must add the getUserId() getter method if you do not already have one.

+16
source

All Articles