我想知道如何通过Spring Security在会话中正确存储和检索我的用户。我正在使用AuthenticationManager。到目前为止,我使用以下方法,我知道这不是最干净的
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value="/myAccount", method=RequestMethod.GET)
public void myAccount(HttpServletRequest request){
//Verify Logged in user
User user = null;
UserProfile loggedinUser = (UserProfile) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(loggedinUser != null){
user = userService.loadUserByUsername(loggedinUser.getUsername());
}
//Store User in session
Session session = request.getSession(true);
session.setAttribute("user", user);
}
}
我在这里看了答案:Set User Object in session using Spring
但我不完全明白应该如何实施它。我可以像这样实现我的用户类
public class User implements UserDetails {
private String username;
private String password;
private String email;
......
}
然后像这样修改我的控制器
public class UserController {
@Autowired
private UserDetailsService userDetailsService;
@RequestMapping(value="/myAccount", method=RequestMethod.GET)
public void myAccount(){
User user = (User)SecurityContextHolder.
getContext().getAuthentication().getPrincipal();
}
}
根据我的理解,Spring会自动从数据库加载我的自定义用户并将其存储在会话中吗?
由于