get login username with Spring Security

Asked

Viewed 2,602 times

5

Hello, I come here to ask for help about Spring Security.

I would like to know how I can get the username logged in. 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();

    }
  • Hello! Could you pass us the code you are using to get the login? Just to have a basis of what you have tried to do. You’ll probably get the information you need on SecurityContextHolder.getContext().getAuthentication().

  • Thank you for Reply Dherik

  • What are the fields in the User class? The name you want is in this class?

1 answer

2

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

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

String nome;    

if (principal instanceof UserDetails) {
    nome = ((UserDetails)principal).getUsername();
} else {
    nome = principal.toString();
}
  • but this variable name I pass it where?

  • @Dherik, within an Async method this may fail?

  • @Danilo will not fail

  • @The name variable was just to illustrate how to get the logged-in user information

Browser other questions tagged

You are not signed in. Login or sign up in order to post.