登录后显示用户详细信息



我正在为我的Web应用程序使用Spring安全性,我想显示一些登录用户的详细信息。在我的代码中,我尝试在登录后对用户本身使用@Autowired,并将其用作模型以在前端显示其某些字段:

  @Autowired
  public AttractionController(XyService xyService, 
  ApplicationUser applicationUser) {
   this.xyService= xyService;
   this.applicationUser = applicationUser;
 }
  @GetMapping("/")
  String main(Model model, @ModelAttribute 
  Attraction xy) {
   model.addAttribute("xy", xyService.findAll());
   model.addAttribute("user", applicationUser);
   return "main";

我认为问题不仅在于实现,还在于方法本身。

我应该如何解决这个问题?

提前谢谢你。

假设ApplicationUser是某种保存用户信息的数据类,那么自动连接它是完全没有意义的,因为它更像是由Spring控制的。

为了获取当前经过身份验证的用户,您只需使用 SecurityContextHolder .可以通过以下方式实例化它:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// check if there is somebody authenticated
if (!(authentication instanceof AnonymousAuthenticationToken)) {
    String currentUserName = authentication.getName();
    // do something the the username, maybe get more information from a database
}

最新更新