How can I use RequestHeader with actuator endpoint?

自古美人都是妖i 提交于 2020-08-24 10:35:02

问题


I have customized my actuator/info endpoint and I want to use information from the header to authorize a RestTemplate call to another service.

I am implementing the InfoContributor as here: https://www.baeldung.com/spring-boot-info-actuator-custom

I want to accept request headers in the contribute() method. For any user defined REST endpoint, I can define a @RequestHeader parameter and access headers.

But unfortunately, the InfoContributor's contribute() method takes only one parameter.

How can I access a request header inside the contribute() method?

Alternative approaches to access the header in an actuator endpoint are welcome.


回答1:


  • You can autowire HttpServletRequest into your InfoContributor
    import javax.servlet.http.HttpServletRequest;

    @Component
    public class Custom implements InfoContributor {

       @Autowired
       private HttpServletRequest request;

       @Override
       public void contribute(Info.Builder builder) {
          ...
          request.getHeader("your header");
          ...
       }
    }
  • Or you can use RequestContextHolder to get hold of it
@Component
public class Custom implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        ...
        HttpServletRequest request = 
           ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                        .getRequest();
        request.getHeader("your header");
       ...
    }
}


来源:https://stackoverflow.com/questions/63072154/how-can-i-use-requestheader-with-actuator-endpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!