Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 757
A_B Avatar asked Mar 16 '17 14:03

A_B


People also ask

Where does Spring Security Store session?

This is the SecurityContextPersistenceFilter. The context will be stored according to the strategy HttpSessionSecurityContextRepository by default, which uses the HTTP Session as storage.

What is SecurityContextHolder Getcontext ()?

The SecurityContext is used to store the details of the currently authenticated user, also known as a principle. So, if you have to get the username or any other user details, you need to get this SecurityContext first. The SecurityContextHolder is a helper class, which provides access to the security context.

Which tag is used to manage session in Spring Security?

SessionManagementFilter in Spring Security web. session. SessionManagementFilter. In XML configuration it's represented by a tag called <session-management />.


1 Answers

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.

like image 163
rvillablanca Avatar answered Oct 18 '22 09:10

rvillablanca