Enterprise Java

Custom Spring Boot Actuator Endpoints

Spring Boot Actuator is a powerful tool that provides production-ready features to monitor and manage your application. It comes with built-in endpoints for health checks, metrics, environment properties, and more. However, in many cases, you may need to extend these capabilities by creating custom endpoints, securing them, or tailoring them to your application’s specific needs.

In this article, we’ll explore:

  1. Creating custom health checks and metrics endpoints.
  2. Securing actuator endpoints with Spring Security.
  3. Best practices and opinions from the developer community.

1. Creating Custom Health Checks and Metrics Endpoints

1.1 Custom Health Checks

Spring Boot Actuator provides a /health endpoint that shows the health status of your application. You can extend this by creating custom health indicators.

Example: Custom Health Indicator

Let’s say you want to check the health of an external service (e.g., a database or an API).

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
 
@Component
public class ExternalServiceHealthIndicator implements HealthIndicator {
 
    @Override
    public Health health() {
        // Simulate a check to an external service
        boolean isServiceUp = checkExternalService();
 
        if (isServiceUp) {
            return Health.up().withDetail("External Service", "Available").build();
        } else {
            return Health.down().withDetail("External Service", "Unavailable").build();
        }
    }
 
    private boolean checkExternalService() {
        // Logic to check the external service
        return true; // Replace with actual check
    }
}

When you hit the /actuator/health endpoint, you’ll see the custom health indicator in the response:

01
02
03
04
05
06
07
08
09
10
11
{
  "status": "UP",
  "components": {
    "externalService": {
      "status": "UP",
      "details": {
        "External Service": "Available"
      }
    }
  }
}

1.2 Custom Metrics

Spring Boot Actuator integrates with Micrometer, a metrics collection library. You can create custom metrics to track application-specific data.

Example: Custom Metric

Let’s create a custom counter metric to track the number of times a specific method is called.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;
 
@Service
public class MyService {
 
    private final Counter myCounter;
 
    public MyService(MeterRegistry registry) {
        this.myCounter = registry.counter("my.custom.counter");
    }
 
    public void doSomething() {
        // Business logic
        myCounter.increment(); // Increment the counter
    }
}

You can view this metric at the /actuator/metrics/my.custom.counter endpoint.

2. Securing Actuator Endpoints with Spring Security

Actuator endpoints expose sensitive information about your application, so it’s crucial to secure them. Spring Security can help you restrict access to these endpoints.

2.1 Example: Securing Actuator Endpoints

Add Spring Security to your project and configure it to secure actuator endpoints.

Step 1: Add Dependencies

Add the following dependencies to your pom.xml or build.gradle:

1
2
3
4
5
6
7
8
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Step 2: Configure Security

Create a security configuration class to restrict access to actuator endpoints.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
 
@Configuration
@EnableWebSecurity
public class SecurityConfig {
 
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((requests) -> requests
                .requestMatchers("/actuator/**").hasRole("ADMIN") // Secure actuator endpoints
                .anyRequest().permitAll()
            )
            .httpBasic(); // Use HTTP Basic authentication
 
        return http.build();
    }
 
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("password")
            .roles("ADMIN")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

Now, only users with the ADMIN role can access actuator endpoints. You can test this by visiting /actuator/health and providing the credentials (admin/password).

3. Best Practices and Opinions

3.1 Best Practices

  • Limit Exposure: Only expose actuator endpoints that are necessary. Use the management.endpoints.web.exposure.include and exclude properties in application.properties or application.yml to control this.
1
2
3
4
5
management:
  endpoints:
    web:
      exposure:
        include: health,metrics,info
  • Use HTTPS: Always secure actuator endpoints over HTTPS to prevent sensitive data from being intercepted.
  • Monitor Access: Log access to actuator endpoints and set up alerts for unusual activity.
  • Customize Health Checks: Add health checks for critical components (e.g., databases, external APIs) to ensure your application is functioning correctly.
  • Use Micrometer for Metrics: Leverage Micrometer to integrate with monitoring systems like Prometheus, Grafana, or Datadog.

To illustrate them better we present the best practises into a table format as well

Best PracticeDescription
Limit ExposureOnly expose necessary actuator endpoints using management.endpoints.web.exposure.include and exclude.
Use HTTPSSecure actuator endpoints over HTTPS to prevent sensitive data interception.
Monitor AccessLog access to actuator endpoints and set up alerts for unusual activity.
Customize Health ChecksAdd health checks for critical components (e.g., databases, external APIs).
Use Micrometer for MetricsIntegrate with monitoring systems like Prometheus, Grafana, or Datadog.
Role-Based Access ControlRestrict access to actuator endpoints using roles (e.g., ADMIN).
Regularly Update DependenciesKeep Spring Boot, Actuator, and Spring Security dependencies up to date.
Disable Sensitive EndpointsDisable endpoints like env and configprops in production unless absolutely necessary.

4. Opinions from the Community

The developer community has shared valuable insights on using Spring Boot Actuator effectively. Here are some key opinions:

  1. Custom Endpoints Are Essential: Many developers advocate for creating custom actuator endpoints to monitor application-specific metrics and health checks. This provides deeper insights into the application’s behavior and performance. According to Baeldung, custom health indicators are a great way to extend the default health checks provided by Spring Boot Actuator.
  2. Security Should Be a Priority: The community strongly emphasizes securing actuator endpoints, especially in production environments. Exposing sensitive data without proper authentication can lead to security vulnerabilities. As highlighted in a DZone article, securing actuator endpoints with Spring Security is a best practice that should not be overlooked.
  3. Minimal Exposure by Default: Some developers recommend exposing only the /health and /info endpoints by default. Additional endpoints should be enabled only when necessary to reduce the attack surface. This opinion is supported by the Spring Boot documentation, which advises careful management of endpoint exposure.
  4. Integration with Monitoring Tools: Developers often highlight the importance of integrating actuator metrics with tools like Prometheus and Grafana for real-time monitoring and visualization. The Micrometer documentation provides extensive guidance on how to achieve this integration effectively.
  5. Regular Audits and Updates: The community suggests regularly auditing actuator configurations and updating dependencies to ensure the latest security patches and features are applied. This is a recurring theme in discussions on platforms like Stack Overflow and Reddit.

By incorporating these opinions and best practices, you can ensure that your Spring Boot Actuator implementation is both effective and secure.

5. References

Eleftheria Drosopoulou

Eleftheria is an Experienced Business Analyst with a robust background in the computer software industry. Proficient in Computer Software Training, Digital Marketing, HTML Scripting, and Microsoft Office, they bring a wealth of technical skills to the table. Additionally, she has a love for writing articles on various tech subjects, showcasing a talent for translating complex concepts into accessible content.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button