根据我的理解,在Spring Security中,有多种不同的方法来获取经过身份验证的用户名。
我目前是通过将Principal
包含为控制器方法参数来获取用户名:
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal) {
modelAndView.addObject("email", principal.getName());
// Render template located at src/main/resources/templates/dashboard.html
modelAndView.setViewName("dashboard");
return modelAndView;
}
Spring Security提供了一种简单的方式,使我可以将用户对象存储到会话中,以便任何控制器方法都可以轻松地检索它吗?
我想避免每次执行数据库查询:
// Lookup user in database by e-mail
User user = userService.findUserByEmail(principal.getName());
我正在使用Spring Security 4.2。
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String currentPrincipalName = authentication.getName();
- Matej MarconakUserDetailsService
,在其中返回带有所需数据的自定义UserDetails
- 然后该数据应该在principal中。 - Matej Marconak