在Web應用程序中。是如此普遍,存儲在會話的用戶的詳細信息,但是,如果在春季啓動配置你SecurityConfig
類,如下所示:Spring Boot應用程序。 SecurityContextHolder與HttpSession
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userSecurityService)
.passwordEncoder(passwordEncoder());
}
...
}
和
@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;
}
}
和
public class User implements Serializable, UserDetails {
..
}
那麼你可以記錄所有來自登錄用戶的信息,始終使用
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()
所以..在HttpSession
中存儲用戶信息是一個不好的做法,舊的做法或我錯過了什麼?