views:

149

answers:

2

When dealing with Spring Security do you usually store the current user into a session variable or do you hit the DB every single time you want to access some user information?

At the moment I do the following but it seems a bit wasteful:

public class CurrentUserService {
    private UserDAO userDAO;



    public CurrentUserService(UserDAO userDAO) {
        super();
        this.userDAO = userDAO;
    }

    public User getUser(){
        String username=SecurityContextHolder.getContext().getAuthentication().getName();
        return userDAO.findUser(username);
    }
}
A: 

Keep in mind that the user object to be stored in the session need not be the same you retrieved from the database. A generally acceptable approach is you store the frequently required details of the user in the session and hit the database only for the data that is accessed less frequently. Well, what user information to store in the session and what not to store is totally application dependent.

Gopi
A: 

Spring Security will automatically store the authenticated User object in the session in it's default configuration. One of the first things the Security Filter Chain does is check the session for a valid Authentication Token, if present then it populates the SecurityContext with it and skips any new authentication filters. All you need to do is write your UserDetailsService and the filter chain should od the rest.

Gandalf