get username logged in with Spring Security

3

Hello, I came here to ask for help on Spring Security.

I would like to know how I can get the username of the logged in user. I use authentication with login and password but when I use the search method it returns me the login, and I need to get the username.

public String getUsuarioLogado() {
            FacesContext context = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
            usuarioLogado = (Usuario) session.getAttribute("usuarioLogado");
            Authentication authentication = (Authentication) SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null) {
               authentication.getName();
            }
            return authentication.getName();

    }
    
asked by anonymous 26.04.2018 / 21:50

1 answer

0

The way easier to access user information logged in is SecurityContextHolder :

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
    String nome = ((UserDetails)principal).getUsername();
} else {
    String nome = principal.toString();
}
    
26.04.2018 / 21:56