Spring Boot Actuator: watching and controlling a running application
Actuator gives a running Spring Boot application endpoints for health, build info, metrics, configuration and log levels. This page runs each one against a live server, shows what is exposed by default and why, and builds health groups, a custom endpoint and role-based security around them.
Contents
What Spring Boot Actuator adds
A running application should be able to answer questions from the outside: is it healthy, which version is deployed, how many requests has it served, which configuration value is in effect, and what are its threads doing. Spring Boot Actuator answers them through endpoints, small built-in operations that each expose one kind of information.
Adding spring-boot-starter-actuator
- Endpoints:
,health ,info ,metrics ,env and more. Each is a bean with read and write operations, independent of any transport.loggers - Exposure: the endpoints are published over HTTP under
, and over JMX. By default only/actuator is published, because the others can reveal internals.health - Micrometer: the metrics library behind
. Spring Boot registers JVM, process and HTTP meters automatically, and your code adds its own through/actuator/metrics .MeterRegistry
| Endpoint | Shows | Typical consumer |
|---|---|---|
health | UP or DOWN, with optional details per component | Load balancers, Kubernetes probes |
info | Version, build and git data, custom details | Dashboards, release checks |
metrics | Meters by name, with tags | People exploring; scrapers use prometheus |
envconfigprops | Property sources and bound configuration, sanitised | Debugging configuration |
loggers | Log levels, changeable at runtime | Debugging production |
threaddumpheapdump | Thread stacks, a heap snapshot | Diagnosing hangs and leaks |
mappingsbeansconditions | Request mappings, beans, auto-configuration decisions | Understanding the application |
The programs on this page run Spring Boot 4.1.2 with Spring MVC on a random port, call the endpoints with java.net.http.HttpClientHealthIndicatorHealthorg.springframework.boot.health.contributororg.springframework.boot.actuate.health
What is exposed by default
The same application runs twice, first with no actuator settings and then with every endpoint exposed, and asks for four endpoints each time:
package actuator.basics;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
@SpringBootApplication
public class ActuatorBasics {
static final HttpClient HTTP = HttpClient.newHttpClient();
static HttpResponse<String> get(int port, String path) throws Exception {
HttpRequest request = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + path)).build();
return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
}
static void run(String label, Map<String, Object> properties) throws Exception {
System.out.println(label);
SpringApplication app = new SpringApplication(ActuatorBasics.class);
app.setDefaultProperties(properties);
try (var context = app.run()) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
JsonNode links = JsonMapper.shared().readTree(get(port, "/actuator").body())
.get("_links");
System.out.println(" GET /actuator lists: " + new TreeSet<>(links.propertyNames()));
for (String path : new String[] {"/actuator/health", "/actuator/info",
"/actuator/env", "/actuator/beans"}) {
HttpResponse<String> response = get(port, path);
String body = response.statusCode() == 404 ? "" : response.body();
System.out.println(" GET " + path + " -> " + response.statusCode() + " "
+ (body.length() > 60 ? body.substring(0, 60) + "..." : body));
}
}
}
public static void main(String[] args) throws Exception {
Map<String, Object> base = Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"logging.level.root", "WARN");
run("1. Defaults:", base);
var all = new HashMap<>(base);
all.put("management.endpoints.web.exposure.include", "*");
run("2. management.endpoints.web.exposure.include=*", all);
}
}
1. Defaults:
GET /actuator lists: [health, health-path, self]
GET /actuator/health -> 200 {"groups":["liveness","readiness"],"status":"UP"}
GET /actuator/info -> 404
GET /actuator/env -> 404
GET /actuator/beans -> 404
2. management.endpoints.web.exposure.include=*
GET /actuator lists: [beans, conditions, configprops, configprops-prefix, env, env-toMatch, health, health-path, info, loggers, loggers-name, mappings, metrics, metrics-requiredMetricName, sbom, sbom-id, scheduledtasks, self, threaddump]
GET /actuator/health -> 200 {"groups":["liveness","readiness"],"status":"UP"}
GET /actuator/info -> 200 {}
GET /actuator/env -> 200 {"activeProfiles":[],"defaultProfiles":["default"],"property...
GET /actuator/beans -> 200 {"contexts":{"application":{"beans":{"endpointCachingOperati...
- With the defaults,
listed only/actuator (plushealth , the link template for one component, andhealth-path ).self ,info andenv returned 404: they exist, but are not exposed over HTTP.beans - The health response shows only the overall
and the names of two groups,status andliveness . Details are hidden unless you ask for them.readiness - With
, 12 endpoints appeared, includingexposure.include=* , which serves the software bill of materials when the build produces one. Thesbom ,-name and-prefix entries are link templates for one item.-toMatch now answered, but withinfo : nothing contributes to it until you configure it, as a later section shows.{} andheapdump are missing even withshutdown . Access to those two is restricted by default, and* grants it.management.endpoint.<id>.access=unrestricted
Exposure and access are separate settings. management.endpoints.web.exposure.includeexcludemanagement.endpoint.<id>.accessnoneread-onlyunrestrictedmanagement.endpoint.<id>.enabled*
Health checks, groups and probes
Health is the endpoint other systems depend on. An order service that calls a payment gateway is a typical case: the program adds a health indicator for the gateway, turns the gateway off halfway, and then marks the application as not ready:
package actuator.health;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.boot.health.contributor.Health;
import org.springframework.boot.health.contributor.HealthIndicator;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;
@SpringBootApplication
public class HealthChecks {
@Component("paymentGatewayHealthIndicator")
static class PaymentGatewayHealthIndicator implements HealthIndicator {
final AtomicBoolean reachable = new AtomicBoolean(true);
@Override
public Health health() {
if (reachable.get()) {
return Health.up().withDetail("provider", "stripe").build();
}
return Health.down().withDetail("provider", "stripe")
.withDetail("error", "connect timed out").build();
}
}
static final HttpClient HTTP = HttpClient.newHttpClient();
static final JsonMapper PRETTY = JsonMapper.builder()
.enable(SerializationFeature.INDENT_OUTPUT).build();
static void get(int port, String path, boolean pretty) throws Exception {
HttpRequest request = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + path)).build();
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("GET " + path + " -> " + response.statusCode());
System.out.println(pretty
? PRETTY.writeValueAsString(PRETTY.readTree(response.body()))
: " " + response.body());
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(HealthChecks.class);
app.setDefaultProperties(Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"management.health.diskspace.enabled", "false",
"management.health.ssl.enabled", "false",
"management.endpoint.health.show-details", "always",
"management.endpoint.health.group.checkout.include", "paymentGateway,ping"));
try (var context = app.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
get(port, "/actuator/health", true);
context.getBean(PaymentGatewayHealthIndicator.class).reachable.set(false);
System.out.println("-- payment gateway goes down --");
get(port, "/actuator/health/checkout", false);
get(port, "/actuator/health/liveness", false);
System.out.println("-- application refuses traffic --");
AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC);
get(port, "/actuator/health/readiness", false);
}
}
}
GET /actuator/health -> 200
{
"components" : {
"livenessState" : {
"status" : "UP"
},
"paymentGateway" : {
"details" : {
"provider" : "stripe"
},
"status" : "UP"
},
"ping" : {
"status" : "UP"
},
"readinessState" : {
"status" : "UP"
}
},
"groups" : [ "checkout", "liveness", "readiness" ],
"status" : "UP"
}
-- payment gateway goes down --
GET /actuator/health/checkout -> 503
{"components":{"paymentGateway":{"details":{"provider":"stripe","error":"connect timed out"},"status":"DOWN"},"ping":{"status":"UP"}},"status":"DOWN"}
GET /actuator/health/liveness -> 200
{"status":"UP"}
-- application refuses traffic --
GET /actuator/health/readiness -> 503
{"status":"OUT_OF_SERVICE"}
- The bean
appears as the componentpaymentGatewayHealthIndicator : Spring Boot drops thepaymentGateway suffix from the bean name.HealthIndicator - With
, each component and its details are listed.show-details=always always reports UP, andping andlivenessState reflect the application's availability state.readinessState - Once the gateway was down, the custom
group, which includes onlycheckout andpaymentGateway , returned HTTP 503 with status DOWN. A DOWN or OUT_OF_SERVICE status maps to 503 by default, so a load balancer stops sending traffic without parsing the body.ping - The
group still returned 200. It contains onlyliveness , so a broken dependency did not tell Kubernetes to restart a process that is otherwise fine.livenessState - After
,AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC) returned 503 withreadiness . Spring Boot publishes the same event itself while the application starts and shuts down.OUT_OF_SERVICE
Keep liveness free of external checks: if the database is down, restarting every instance will not fix it. Put dependencies that must be available before taking traffic in the readiness group with management.endpoint.health.group.readiness.include=readinessState,db
Info and env: what is deployed and how it is configured
An infoenvenv
package actuator.info;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
@SpringBootApplication
public class InfoAndEnv {
@Component
static class FeatureFlagsInfo implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("features", Map.of("newCheckout", true));
}
}
static final HttpClient HTTP = HttpClient.newHttpClient();
static String get(int port, String path) throws Exception {
HttpRequest request = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + path)).build();
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(" GET " + path + " -> " + response.statusCode());
return response.body();
}
static void run(String label, String showValues) throws Exception {
System.out.println(label);
Map<String, Object> props = new HashMap<>(Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"management.endpoints.web.exposure.include", "info,env",
"management.info.env.enabled", "true",
"info.app.name", "order-service",
"info.app.version", "1.4.2",
"payment.api-key", "sk_live_51H8"));
if (showValues != null) {
props.put("management.endpoint.env.show-values", showValues);
}
SpringApplication app = new SpringApplication(InfoAndEnv.class);
app.setDefaultProperties(props);
try (var context = app.run()) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
System.out.println(" " + get(port, "/actuator/info"));
JsonNode env = JsonMapper.shared().readTree(get(port, "/actuator/env/payment.api-key"));
System.out.println(" property: " + env.get("property"));
}
}
public static void main(String[] args) throws Exception {
run("1. Default sanitising:", null);
run("2. management.endpoint.env.show-values=always:", "always");
}
}
1. Default sanitising:
GET /actuator/info -> 200
{"app":{"version":"1.4.2","name":"order-service"},"features":{"newCheckout":true}}
GET /actuator/env/payment.api-key -> 200
property: {"source":"defaultProperties","value":"******"}
2. management.endpoint.env.show-values=always:
GET /actuator/info -> 200
{"app":{"version":"1.4.2","name":"order-service"},"features":{"newCheckout":true}}
GET /actuator/env/payment.api-key -> 200
property: {"source":"defaultProperties","value":"sk_live_51H8"}
andinfo.app.name appeared underinfo.app.version becauseapp switches on the contributor that copies everymanagement.info.env.enabled=true property. It has been off by default since Spring Boot 2.6.info.*- The
entry came from the customfeatures bean, which can add any data computed at request time.InfoContributor named the source,/actuator/env/payment.api-key , but returned the value asdefaultProperties . Every value is masked by default.******- With
, the real key was returned to anyone who can reach the endpoint. Useshow-values=always with a role instead, as the security section shows.when-authorized
Two more contributors are on by default but need input from the build: buildMETA-INF/build-info.propertiesbuild-infospringBoot.buildInfo()gitgit.propertiesjavaosprocess
Metrics and runtime log levels
An order endpoint with its own counter and a debug log line shows the two endpoints used most when something goes wrong in production. The debug line only appears once the log level is raised through loggers
package actuator.metrics;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
@SpringBootApplication
public class MetricsAndLoggers {
@RestController
static class OrderController {
private static final Logger log = LoggerFactory.getLogger(OrderController.class);
private final Counter placed;
OrderController(MeterRegistry registry) {
this.placed = Counter.builder("orders.placed")
.tag("channel", "web")
.description("Orders accepted")
.register(registry);
}
@PostMapping("/orders")
String place() {
placed.increment();
log.debug("order accepted, total so far {}", (long) placed.count());
return "ok";
}
}
static final HttpClient HTTP = HttpClient.newHttpClient();
static String call(int port, String method, String path, String json) throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + path));
if (json != null) {
builder.header("Content-Type", "application/json");
}
builder.method(method, json == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(json));
HttpResponse<String> response = HTTP.send(builder.build(),
HttpResponse.BodyHandlers.ofString());
System.out.println(method + " " + path + " -> " + response.statusCode());
System.out.flush();
return response.body();
}
static JsonNode json(String body) {
return JsonMapper.shared().readTree(body);
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(MetricsAndLoggers.class);
app.setDefaultProperties(Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"spring.main.log-startup-info", "false",
"logging.level.actuator.metrics", "INFO",
"logging.pattern.console", " log: %level %logger{0} - %m%n",
"management.endpoints.web.exposure.include", "health,metrics,loggers"));
try (var context = app.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String logger = "/actuator/loggers/actuator.metrics.MetricsAndLoggers$OrderController";
call(port, "POST", "/orders", null);
System.out.println(" " + json(call(port, "GET", logger, null)));
call(port, "POST", logger, "{\"configuredLevel\":\"DEBUG\"}");
call(port, "POST", "/orders", null);
call(port, "POST", "/orders", null);
System.out.println(" " + json(call(port, "GET", logger, null)));
JsonNode orders = json(call(port, "GET", "/actuator/metrics/orders.placed", null));
System.out.println(" measurements: " + orders.get("measurements"));
System.out.println(" tags: " + orders.get("availableTags"));
JsonNode http = json(call(port, "GET",
"/actuator/metrics/http.server.requests?tag=uri:/orders", null));
System.out.println(" COUNT for uri=/orders: "
+ http.get("measurements").get(0).get("value"));
JsonNode names = json(call(port, "GET", "/actuator/metrics", null)).get("names");
for (String name : new String[] {"jvm.memory.used", "jvm.threads.live",
"process.cpu.usage", "tomcat.sessions.active.current"}) {
boolean found = false;
for (JsonNode n : names) {
found |= n.asString().equals(name);
}
System.out.println(" " + name + " listed: " + found);
}
}
}
}
POST /orders -> 200
GET /actuator/loggers/actuator.metrics.MetricsAndLoggers$OrderController -> 200
{"effectiveLevel":"INFO"}
POST /actuator/loggers/actuator.metrics.MetricsAndLoggers$OrderController -> 204
log: DEBUG MetricsAndLoggers$OrderController - order accepted, total so far 2
POST /orders -> 200
log: DEBUG MetricsAndLoggers$OrderController - order accepted, total so far 3
POST /orders -> 200
GET /actuator/loggers/actuator.metrics.MetricsAndLoggers$OrderController -> 200
{"configuredLevel":"DEBUG","effectiveLevel":"DEBUG"}
GET /actuator/metrics/orders.placed -> 200
measurements: [{"statistic":"COUNT","value":3.0}]
tags: [{"tag":"channel","values":["web"]}]
GET /actuator/metrics/http.server.requests?tag=uri:/orders -> 200
COUNT for uri=/orders: 3.0
GET /actuator/metrics -> 200
jvm.memory.used listed: true
jvm.threads.live listed: true
process.cpu.usage listed: true
tomcat.sessions.active.current listed: true
- The first order produced no log line: the controller's logger was at INFO.
showed only anGET /actuator/loggers/... , inherited from a parent logger.effectiveLevel withPOST returned 204, and the next two orders logged at DEBUG. The logger now reports both a configured and an effective level. Posting{"configuredLevel":"DEBUG"} resets it.{"configuredLevel":null} counted all 3 orders, including the one before the level change, and lists itsorders.placed tag with the valuechannel .web , recorded automatically for every request, filtered withhttp.server.requests , also counted 3. The?tag=uri:/orders tag holds the route template, not the raw path, souri stays one series./orders/{id}- JVM memory, thread, CPU and Tomcat meters were registered without any code.
The metricsmicrometer-registry-prometheusprometheusloggers
Writing your own endpoint
Operational controls that are specific to your application, such as feature flags, fit an endpoint of their own. The program also moves all actuator endpoints to a separate management port, which keeps them away from public traffic:
package actuator.custom;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class CustomEndpoint {
@Component
@Endpoint(id = "features")
static class FeaturesEndpoint {
private final Map<String, Boolean> flags = new ConcurrentHashMap<>(
Map.of("newCheckout", false, "giftCards", true));
@ReadOperation
Map<String, Boolean> all() {
return new TreeMap<>(flags);
}
@ReadOperation
Boolean one(@Selector String name) {
return flags.get(name);
}
@WriteOperation
void set(@Selector String name, boolean enabled) {
flags.put(name, enabled);
}
}
static final HttpClient HTTP = HttpClient.newHttpClient();
static void call(int port, String label, String method, String path, String json)
throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + path))
.header("Content-Type", "application/json")
.method(method, json == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
String body = response.statusCode() == 404 ? "" : response.body();
System.out.println(label + " " + method + " " + path + " -> "
+ response.statusCode() + " " + body);
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(CustomEndpoint.class);
app.setDefaultProperties(Map.of(
"server.port", "0",
"management.server.port", "0",
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"management.endpoints.web.exposure.include", "health,features"));
try (var context = app.run(args)) {
int appPort = ((WebServerApplicationContext) context).getWebServer().getPort();
int mgmtPort = context.getEnvironment()
.getRequiredProperty("local.management.port", Integer.class);
System.out.println("separate ports: " + (appPort != mgmtPort));
call(appPort, "[app] ", "GET", "/actuator/health", null);
call(mgmtPort, "[mgmt]", "GET", "/actuator/health", null);
call(mgmtPort, "[mgmt]", "GET", "/actuator/features", null);
call(mgmtPort, "[mgmt]", "POST", "/actuator/features/newCheckout",
"{\"enabled\": true}");
call(mgmtPort, "[mgmt]", "GET", "/actuator/features/newCheckout", null);
call(mgmtPort, "[mgmt]", "GET", "/actuator/features/unknown", null);
}
}
}
separate ports: true
[app] GET /actuator/health -> 404
[mgmt] GET /actuator/health -> 200 {"groups":["liveness","readiness"],"status":"UP"}
[mgmt] GET /actuator/features -> 200 {"giftCards":true,"newCheckout":false}
[mgmt] POST /actuator/features/newCheckout -> 204
[mgmt] GET /actuator/features/newCheckout -> 200 true
[mgmt] GET /actuator/features/unknown -> 404
- With
set, the endpoints moved to a second port:management.server.port on the application port returned 404, and on the management port 200. The real port numbers are random here, so the program only checks that they differ./actuator/health became@Endpoint(id = "features") , once listed in/actuator/features . Theexposure.include without parameters answered@ReadOperation .GET /actuator/features- A
parameter becomes a path segment, so@Selector calledGET /actuator/features/newCheckout .one("newCheckout") - The
took@WriteOperation from the JSON body and returned 204, because it returns nothing. The flag then readenabled .true - For an unknown name,
returnedone , which Actuator turns into 404.null
The same endpoint is also published over JMX when spring.jmx.enabled=true@DeleteOperation@WebEndpoint
Securing the endpoints
With Spring Security on the classpath, Spring Boot secures every actuator endpoint except healthEndpointRequest
package actuator.security;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.health.actuate.endpoint.HealthEndpoint;
import org.springframework.boot.security.autoconfigure.actuate.web.servlet.EndpointRequest;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import tools.jackson.databind.json.JsonMapper;
@SpringBootApplication
public class ActuatorSecurity {
@Bean
SecurityFilterChain actuatorChain(HttpSecurity http) throws Exception {
http.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth
.requestMatchers(EndpointRequest.to(HealthEndpoint.class)).permitAll()
.anyRequest().hasRole("OPS"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
UserDetailsService users() {
return new InMemoryUserDetailsManager(
User.withUsername("ops").password("{noop}ops-secret").roles("OPS").build(),
User.withUsername("dev").password("{noop}dev-secret").roles("DEV").build());
}
static final HttpClient HTTP = HttpClient.newHttpClient();
static void get(int port, String path, String user) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + path));
if (user != null) {
String token = Base64.getEncoder().encodeToString(
(user + ":" + user + "-secret").getBytes(StandardCharsets.UTF_8));
request.header("Authorization", "Basic " + token);
}
HttpResponse<String> response = HTTP.send(request.build(),
HttpResponse.BodyHandlers.ofString());
String body = response.statusCode() != 200 ? ""
: path.contains("/env/") ? "property " + JsonMapper.shared()
.readTree(response.body()).get("property")
: response.body();
System.out.println((user == null ? "anonymous" : user) + " GET " + path + " -> "
+ response.statusCode() + " "
+ (body.length() > 70 ? body.substring(0, 70) + "..." : body));
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(ActuatorSecurity.class);
app.setDefaultProperties(Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"management.health.diskspace.enabled", "false",
"management.health.ssl.enabled", "false",
"management.endpoints.web.exposure.include", "health,env,loggers",
"management.endpoint.health.show-details", "when-authorized",
"management.endpoint.health.roles", "OPS",
"management.endpoint.env.show-values", "when-authorized",
"management.endpoint.env.roles", "OPS"));
try (var context = app.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
get(port, "/actuator/health", null);
get(port, "/actuator/health", "ops");
get(port, "/actuator/env/server.port", null);
get(port, "/actuator/env/server.port", "dev");
get(port, "/actuator/env/server.port", "ops");
}
}
}
anonymous GET /actuator/health -> 200 {"groups":["liveness","readiness"],"status":"UP"}
ops GET /actuator/health -> 200 {"components":{"livenessState":{"status":"UP"},"ping":{"status":"UP"},...
anonymous GET /actuator/env/server.port -> 401
dev GET /actuator/env/server.port -> 403
ops GET /actuator/env/server.port -> 200 property {"source":"defaultProperties","value":"0"}
- Anonymous callers got
with only the overall status. Thehealth user got the components too, becauseops withshow-details=when-authorized shows details only to that role.roles=OPS returned 401 without credentials and 403 forenv , who is authenticated but lacks thedev role.OPS got 200 and the unmasked valueops , because0 with the same role reveals values only to that role.show-values=when-authorized
EndpointRequestorg.springframework.boot.security.autoconfigure.actuate.web.servletmanagement.endpoints.web.base-path
Choosing what to expose
| Need | Setting |
|---|---|
| Load balancer or Kubernetes probes | healthlivenessreadiness |
| A health view of one feature | management.endpoint.health.group.<name>.include |
| Which version is deployed | info |
| Metrics in a monitoring system | A Prometheus or OTLP registry, not the metrics |
| Debugging one instance in production | loggersthreaddumpenv |
| Application-specific operations | A custom @Endpoint |
| Keeping endpoints off the public network | management.server.port |
Secrets in envconfigprops | Keep the default masking, or show-values=when-authorized |
Start with healthinfometricsenvloggers