首页 > 解决方案 > 为什么 Spring Boot Microservice 的参数 Principal 为 null 值,如何获取客户端应用程序的实际值?

问题描述

在 Spring Boot 中,我有以下微服务,它需要 Principal 对象才能访问登录的用户信息:

        @RequestMapping(value="/circular-save")
        public Boolean saveCircularView(HttpServletRequest request, Principal principal, HttpSession session, Locale locale, ModelAndView mav,
                @ModelAttribute CircularsBean souqBean) {


            System.out.println( "circular-save microservice Called...........principal="+principal);

            //some user related code here that depends on principal
    }

输出:

circular-save microservice Called.....................principal=null

我将上述微服务称为:

System.out.println("Will call circulars with principal:"+principal.getName());
restTemplate.getForObject("http://localhost:8081/circular-save", Boolean.class);

输出:

Will call circulars with principal:travelling.salesman

如您所见,principal 值在客户端不为 null,但在服务器端为 null。如何正确地让这个主体对象在微服务之间传递?

我的研究:

起初,我正在考虑在 json 请求中传递它并使用 POST 方法,但我失败了,因为它不是 POJO 并且无法序列化它。

我做了更多的研究,发现这行可以写在服务器端。

principal = SecurityContextHolder.getContext().getAuthentication();

不幸的是,上述解决方案给了我不同的对象,导致匿名用户与原始用户不同。

我将不胜感激任何帮助。谢谢。

标签: javajsonspringspring-bootprincipal

解决方案


推荐阅读