Search code examples
javaspring-mvcjakarta-eespring-bootjava-ee-7

Spring Boot apps. SecurityContextHolder vs. HttpSession


In Web app. is so common to store the user details in the session, But if in Spring Boot you configure you SecurityConfig class as follows:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {                  

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userSecurityService)
           .passwordEncoder(passwordEncoder());
    }
...
}

and

@Service
public class UserSecurityService implements UserDetailsService {

    /** The application logger */
    private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        LOG.info("Searching user with email: " + email);

        User user = userRepository.findByEmail(email);

        if (null == user) {
            LOG.warn("Username {} not found", email);
            throw new UsernameNotFoundException("Username " + email + " not found");
        }
        return user;
    }
}

and

public class User implements Serializable, UserDetails {
..
}

then you can grap all the info from the logged user using always

User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()

so.. storing the user info in the HttpSession is a bad practice, old practice or I miss something ?


Solution

  • Spring Security is a security framework and can be used in both web and standalone applications. The SecurityContextHolder provides a unified way of obtaining the SecurityContext and in the end the User.

    When using Spring Security in a web application the storage of the SecurityContext is delegated to the SecurityContextRepository and the default implementation used is the HttpSessionSecurityContextRepository so in the end it still stores it in the HttpSession but you could also create your own implementation and store it else where (a database, Redis, etc.).

    In short the SecurityContextHolder is thus a unified way to get the SecurityContext used by Spring Security without you having to know in all the places how/where it is stored.