19

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()
    );
}

1 Answer 1

31
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.

2
  • 4
    Principal can be injected. May 29, 2015 at 6:13
  • 9
    Injection via method parameter: @AuthenticationPrincipal CustomUser customUser
    – Tom
    Nov 15, 2017 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.