Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

546
Visualizações
Store User object in session with Spring Security

Based on my understanding, there are a number of different ways to retrieve the authenticated username in Spring Security.

I'm currently grabbing the username by included the Principal as a controller method argument:

@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal) {

  modelAndView.addObject("email", principal.getName());

  // Render template located at src/main/resources/templates/dashboard.html
  modelAndView.setViewName("dashboard");

  return modelAndView;
}

Does Spring Security offer an easy way for me to store the User object into the session so it can be easily retrieved by any controller method?

I want to avoid performing a DB lookup each time:

// Lookup user in database by e-mail
User user = userService.findUserByEmail(principal.getName());

I'm using Spring Security 4.2.

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Spring Security provides you with a static method for quickly and easy access:

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

Or

User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();

Maybe you would like do this in a base abstract class

public abstract class BaseController {
    protected User getCurrentUser() {
        return (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}
...
public YourController extends BaseController {
...
}

Update

If you want to store the current authenticated user in session, then you need store only first time in a object as suggested by @gkatzioura.

@Component
@Scope("session")
public class MySessionInfo {

    private User user;

    protected User getCurrentUser() {
        if (user == null) {
            user = userService.findUserByEmail(SecurityContextHolder.getContext().getAuthentication().getPrincipal().getName());
        }
        return user;
    }
}

You can inject this bean in yours controllers like

@Autowired
private MySessionInfo mySessionInfo;

You must take care about cases when user is not logged, but this is another problem.

about 4 years ago · Santiago Trujillo Relatório

0

You can always use the methods that spring security provides to get basic information such as name, authorities and everything provided by the Authentication.class.

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
authentication.getAuthorities();
authentication.getName();

But if you want more information, using a session bean to store the information is also a good idea.

@Component
@Scope("session")
public class UserInfo { .. }
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda