Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

544
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!