Spring安全性从更深层访问UserDetailsS​​ervice

我有以下UserDetailsS​​ervice实现。
到目前为止,身份validation过程非常有效。
如何在“会话”中存储我的“MyUser bean”( 已成功登录 ),以便我可以在我的应用程序的其他区域中访问它

谢谢。

@Transactional(readOnly = true) public class CustomUserDetailsService implements UserDetailsService { private EmployeesApi employeesApi = new EmployeesApi(); /** * Retrieves a user record containing the user's credentials and access. */ public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException { // Declare a null Spring User UserDetails user = null; try { MyUser employee = employeesApi.getByUserName(userName); user = new User( employee.getUserName(), employee.getPassword().toLowerCase(), true, true, true, true, getAuthorities(1) ); } catch (Exception e) { logger.error("Error in retrieving user"); throw new UsernameNotFoundException("Error in retrieving user"); } } .... 

Spring Security已经为您在会话中存储了经过身份validation的用户的UserDetails

因此,在会话中存储MyUser的最简单方法是实现包含对MyUser的引用的自定义UserDetails

 public class MyUserDetails extends User { private MyUser myUser; public MyUserDetails(..., MyUser myUser) { super(...); this.myUser = myUser; } public MyUser getMyUser() { return myUser; } ... } 

并从UserDetailsService返回它:

 MyUser employee = employeesApi.getByUserName(userName); user = new MyUserDetails(..., myUser); 

然后,您可以通过安全上下文轻松访问MyUser

 MyUser myUser = ((MyUserDetails) SecurityContextHolder .getContext().getAuthentication().getPrincipal()).getMyUser(); 

在Spring MVC控制器中:

 @RequestMapping(...) public ModelAndView someController(..., Authentication auth) { MyUser myUser = ((MyUserDetails) auth.getPrincipal()).getMyUser(); ... } 

在JSP中: