0Pricing
Spring Boot 4 Microservices & REST APIs · Урок

Защита конечных точек Actuator

Защищайте важные эксплуатационные конечные точки

«Защита конечных точек Actuator» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Actuator Needs Securing

Actuator endpoints can reveal environment variables, beans, mappings, and even heap dumps. Left open, they leak sensitive information and may allow dangerous operations like shutdown. They must be protected in production.

Minimize the Attack Surface First

Security starts with exposure. Expose only the endpoints operators truly need over HTTP, and exclude sensitive ones like env, beans, and heapdump.

management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus
        exclude: env,beans,heapdump,threaddump

Adding Spring Security

To authenticate access, add Spring Security. Once on the classpath, it secures the application — including Actuator endpoints — and you define the rules.

<!-- pom.xml -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

The EndpointRequest Matcher

Spring Boot provides EndpointRequest matchers so your security config can target Actuator endpoints precisely, without hardcoding the /actuator path.

import static org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest.*;
// EndpointRequest.toAnyEndpoint()
// EndpointRequest.to("health", "info")

Locking Down the Endpoints

A typical policy: allow health and info anonymously (for probes), but require an authenticated role for everything else.

@Bean
SecurityFilterChain actuatorSecurity(HttpSecurity http) throws Exception {
    http.securityMatcher(EndpointRequest.toAnyEndpoint())
        .authorizeHttpRequests(a -> a
            .requestMatchers(EndpointRequest.to("health", "info")).permitAll()
            .anyRequest().hasRole("ADMIN"))
        .httpBasic(Customizer.withDefaults());
    return http.build();
}

Role-Based Access

Restrict management endpoints to an operations role such as ADMIN. Combine with your existing user store — in-memory for demos, a real identity provider in production.

@Bean
UserDetailsService users(PasswordEncoder encoder) {
    UserDetails admin = User.withUsername("ops")
        .password(encoder.encode("change-me"))
        .roles("ADMIN").build();
    return new InMemoryUserDetailsManager(admin);
}

Isolating with a Management Port

Run Actuator on a separate port that is only reachable inside your network or cluster. Public traffic hits the app port; operators reach management through internal routing.

management:
  server:
    port: 8081
# expose 8081 only to the internal network / sidecar

Probes Without Credentials

Kubernetes probes call health/liveness and health/readiness without auth. Permit those specific paths while still protecting the rest of health details and other endpoints.

.requestMatchers(EndpointRequest.to("health")).permitAll()
// keep show-details restricted so anonymous probes see only status

Hiding Health Details

Even when health is public, do not leak component internals to anonymous callers. Set show-details to when-authorized so probes see only UP/DOWN.

management:
  endpoint:
    health:
      show-details: when-authorized

Disable Dangerous Endpoints

Some endpoints can change runtime state. Keep shutdown disabled, and avoid exposing heapdump or threaddump publicly, as they reveal memory contents and aid attackers.

management:
  endpoint:
    shutdown:
      enabled: false

Defense in Depth

No single control suffices. Combine measures:

  • Minimal exposure
  • Authentication and roles
  • Network isolation / separate port
  • Restricted health details

Quick Check

Test your understanding of securing Actuator.

Recap

Treat Actuator as a security perimeter.

  • Expose minimally; exclude env, beans, heapdump
  • Add Spring Security and use EndpointRequest matchers
  • Permit health/info for probes; require a role for the rest
  • Restrict show-details and disable shutdown
  • Isolate via a separate management port

Часто задаваемые вопросы

Урок «Защита конечных точек Actuator» бесплатный?

Да — полный текст урока «Защита конечных точек Actuator» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Чему я научусь в уроке «Защита конечных точек Actuator»?

Защищайте важные эксплуатационные конечные точки Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Защита конечных точек Actuator»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Включение конечных точек Actuator
  2. Индикаторы состояния
  3. Пользовательские метрики с Micrometer
  4. Защита конечных точек Actuator
← Назад к Spring Boot 4 Microservices & REST APIs