How can I use RequestHeader with actuator endpoint?

Viewed 446

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?

1 Answers
  • 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");
       ...
    }
}
Related