如何在ModelAttribute方法中获取Principal对象

问题描述 投票:-1回答:2

我正在尝试加载一些应该可用于每个HTTP请求的基本用户信息。我读到我可以使用带有@ModelAttribute方法的@ControllerAdvice类来完成此操作。例如:

@ControllerAdvice
public class DefaultController{

  @ModelAttribute
  public void load(ModelMap model){


  }

}

但是,我无法访问由Spring Security管理的Principal对象。我尝试过以下方法:

  @ModelAttribute
  public void load(ModelMap model, @AuthenticationPrincipal CustomUser user){


  }

  @ModelAttribute
  public void load(ModelMap model, Principal user){
  //Cast to CustomUser object

  }

但这两个都行不通。我得到用户对象的空值。我想知道是否有人知道如何在@ModelAttribute方法中获取Principal对象

java spring spring-mvc spring-security
2个回答
3
投票

哈哈,所以我真傻。我刚刚意识到,当第一次访问我的主页时,用户未经过身份验证,因此无论如何都不会有spring security中的用户对象。

我只需要首先检查对象是否为空

@ModelAttribute
public void load(ModelMap model, @AuthenticationPrincipal CustomUser user){

 if(user != null){
    long userId = user.getId();
    //Query database with userId and add data to model
 }

}

2
投票

你可以使用Authentication获得一个org.springframework.security.core.context.SecurityContextHolder对象

@ModelAttribute
public void addUserToModel(Model model) {
    try {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        // do something
    } catch (Exception ex) {

    }
}

实际上,您可以在应用程序的任何位置使用SecurityContextHolder

© www.soinside.com 2019 - 2024. All rights reserved.