首页 > 解决方案 > 如何在 RestController 中获取标头值并将其传递给父控制器

问题描述

我是 spring-boot 的新手,对 web 服务也很陌生。

我想在(抽象)通用 RestController 中实现一个授权过程,它应该获取基本身份验证的内容。来自扩展控制器的标头,然后执行授权。

像这样的东西:

public class GenericController
{
  // Constructor 
  protected GenericController(String basicAuth) throws MalformedURLException, ProtocolException, IOException
  {
    // check user can execute action
  }
}


@RestController
@RequestMapping( "/users" )
public class UserController extends GenericController
{
  private static final Logger logger = LoggerFactory.getLogger(UserController.class);
  
  // Constructor
  protected UserController() throws MalformedURLException, ProtocolException, IOException
  {
    // somehow get the basic auth information from header and pass it to the parent's constructor
    basicAuth = ???
    
    super(basicAuth);
  }

  @GetMapping( "/user/{cn}" )
  public String getUser( @PathVariable String cn )
  {
    logger.error("Start getUser(...): cn=" + cn);

  }

我怎样才能做到这一点?(这甚至可能吗?)

附加信息:我的 Web 服务本身就是其他 Web 服务的消费者。

一旦主叫用户被授权“使用”我的 Web 服务,我必须将基本身份验证转发/设置到我调用的 Web 服务的请求中。

那么,当我的服务被调用时,我如何/在哪里“拦截”并获取标头?

标签: javaspring-bootweb-services

解决方案


您可以使用 HttpServletRequest 从请求中获取标头。

 protected UserController(HttpServletRequest httpServletRequest) throws MalformedURLException, ProtocolException, IOException
    {

        System.out.println( httpServletRequest.getHeaders("key name"));
        // somehow get the basic auth information from header and pass it to the parent's constructor
        basicAuth = ???

        super(basicAuth);
    }

推荐阅读