Search code examples
spring-boot-admin

Spring Boot Admin: custom header authentication


My app has a custom authentication mechanism based on a custom HTTP header. AFAIK, Spring Boot Admin supports only Basic auth and OAuth. But maybe there's a way for clients to supply some custom header along with their requests?


Solution

  • Alright, so if both SBA Server and SBA Client are launched along with the monitored application itself, and it has custom-headers security, we need to take care of 3 things:

    1. As Nitin mentioned, one needs to register HttpHeadersProvider bean:
        @Bean
        public HttpHeadersProvider customHttpHeadersProvider() {
            return instance -> {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("X-CUSTOM", "My Custom Value");
                return httpHeaders;
            };
        }
    
    1. Note, that these headers are not applied to OPTIONS requests to the Actuator endpoints, so one would either need to customize ProbeEndpointsStrategy, or disable Spring Security for OPTIONS calls to the management URL. Also, for some reason, I had to disable security for /actuator/health/**, although it should've been accessible with custom header provided:
        @Override
        public void configure(WebSecurity web) {
            web.ignoring().antMatchers(HttpMethod.OPTIONS, "/actuator/**").antMatchers(HttpMethod.GET, "/actuator/health/**");
        }
    
    1. Finally, one needs to instantiate ApplicationRegistrator with a custom RestTemplate that would be pre-populated with a custom header:
        @Bean
        public ApplicationRegistrator registrator(ClientProperties client, ApplicationFactory applicationFactory) {
            RestTemplateBuilder builder = new RestTemplateBuilder()
                    .setConnectTimeout(client.getConnectTimeout())
                    .setReadTimeout(client.getReadTimeout())
                    .additionalInterceptors((request, body, execution) -> {
                        request.getHeaders().set("X-CUSTOM", "My Custom Value");
                        return execution.execute(request, body);
                    });
            if (client.getUsername() != null) {
                builder = builder.basicAuthentication(client.getUsername(), client.getPassword());
            }
            return new ApplicationRegistrator(builder.build(), client, applicationFactory);
        }