Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get User ID from CustomUser on Spring Security

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()
    );
}
like image 413
Joao Evangelista Avatar asked Mar 27 '14 05:03

Joao Evangelista


People also ask

What is Spring Security username?

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

What is SecurityContextHolder getContext () getAuthentication ()?

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.


1 Answers

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.

like image 61
holmis83 Avatar answered Oct 11 '22 13:10

holmis83