Spring Boot apps. SecurityContextHolder vs. HttpSession

Viewed 2602

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 ?

1 Answers
Related