Search code examples
javaspring-bootspring-boot-actuatorcontent-negotiation

How to disable content negotiation for Spring Actuators?


I'd like to disable Content-Negotiation when actuator endpoints /info and /health are called

here is my configs file

@Configuration
public class InterceptorAppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor);
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_XML)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML);
    }
}

When I curl http://localhost:8081/health

I receive:

DefaultHandlerExceptionResolver Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]

However when I fire same url in Chrome, i receive a valid response.

In my case actuator should be called without headers (no -H 'Accept: ...')


Solution

  • Add defaultContentTypeStrategy and handle the null or wildcard accept.

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_XML)
        .mediaType("json", MediaType.APPLICATION_JSON)
        .mediaType("xml", MediaType.APPLICATION_XML);
    
        configurer.defaultContentTypeStrategy(new ContentNegotiationStrategy() {
            @Override
            public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException {
                // If you want handle different cases by getting header with webRequest.getHeader("accept")
                return Arrays.asList(MediaType.APPLICATION_JSON);
            }
        });       
    }