Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

545
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda