# Put a Login on Swagger and Actuator (Before Someone Else Does)

Two endpoints ship with your Spring Boot app that you never wrote and probably stopped thinking about months ago. One hands any visitor a complete, machine-readable map of your entire API. The other will, on request, send them a copy of your application's memory — tokens, passwords, connection strings and all. They're called Swagger and Actuator, you almost certainly turned them on for a good reason in development, and the unpleasant part is that "development" and "production" share the same config more often than anyone admits.

Neither is a bug. Both are features you opted into. The mistake is leaving them standing open to the internet because they were open on your laptop and nothing ever yelled at you to close them.

Let's look at what's actually behind each door, then lock them properly — not with one flag, but in layers.

## What you're actually exposing

![Swagger UI / api-docs hands out your full API surface and schemas; Actuator exposes env, beans, heapdump, loggers and shutdown — config, secrets, and control.](https://cdn.hashnode.com/uploads/covers/6a00c971e3eebc2e20b385b4/7695edef-5785-45bb-9edb-a0a5defbc78a.png align="center")

**Swagger / OpenAPI.** `springdoc` serves `/swagger-ui/index.html` for humans and `/v3/api-docs` as raw JSON for machines. That JSON is the whole thing: every route, every method, every parameter, every request and response schema. For a legitimate consumer it's documentation. For an attacker it's reconnaissance they didn't have to do — your undocumented internal endpoints, your admin routes, your "we'll secure that later" controller, all neatly listed.

**Actuator.** This one's worse, because some of its endpoints don't just *describe* the app, they *operate* it. A quick tour of the sharp ones:

- `/actuator/env` and `/configprops` — your configuration, including a lot of things that were never meant to leave the server.
- `/actuator/beans` and `/mappings` — your whole bean graph and URL map, i.e. the internal architecture.
- `/actuator/heapdump` — downloads a full heap dump. Whatever secrets were sitting in memory are now a file on the attacker's disk.
- `/actuator/loggers` — lets you change log levels at runtime via POST. Crank a package to `DEBUG` and watch the secrets scroll.
- `/actuator/shutdown` — exactly what it says. Disabled by default, but people enable it and forget.

Good news first: by default Boot only exposes `health` over HTTP, and `env` sanitizes obvious keys. The danger is the line that's in half the tutorials on the internet:

```yaml
management:
  endpoints:
    web:
      exposure:
        include: "*"   # <- exposes every actuator endpoint. great in a demo, a gift in prod.
```

Ship that, leave it unauthenticated, and every endpoint above is one `curl` away.

## Lock it in layers, not with one switch

The instinct is to find the single "secure it" setting. There isn't one, and that's fine — defense in depth means each layer assumes the one above it failed.

![Four layers: expose only what you need, authenticate, authorize with ROLE_ADMIN, and isolate onto a separate management port.](https://cdn.hashnode.com/uploads/covers/6a00c971e3eebc2e20b385b4/a5be0681-fe8d-45ff-9056-61f262bc091b.png align="center")

### Layer 1 — expose less

The cheapest fix is the one you skip: don't publish what you don't need. Pin the actuator exposure list to the endpoints you actually use, and never `*` in production.

```yaml
management:
  endpoints:
    web:
      exposure:
        include: health,info     # not "*"
  endpoint:
    health:
      show-details: when-authorized   # full health only after login; anonymous sees just UP/DOWN
```

And Swagger genuinely does not need to exist in production for most apps. Turn it off per profile:

```yaml
# application-prod.yml
springdoc:
  api-docs:
    enabled: false
  swagger-ui:
    enabled: false
```

If you do keep it in prod — internal tools, a partner API — then it has to get the same auth as everything else below. An endpoint that doesn't exist can't be attacked; that's always the strongest version of "secured."

### Layers 2 and 3 — authenticate, then authorize

Add `spring-boot-starter-security`, and the framework gives you a login out of the box. But "logged in" is not the bar for these endpoints — *admin* is. The distinction matters: a regular user account that gets phished shouldn't come with a heap dump button.

Spring Security's `EndpointRequest` matchers know about actuator, so you don't hand-write the paths:

```java
@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            // health + info stay open for load balancers and uptime checks
            .requestMatchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)).permitAll()
            // every OTHER actuator endpoint: admins only
            .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
            // Swagger UI + the raw OpenAPI doc: admins only
            .requestMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").hasRole("ADMIN")
            // your real application rules
            .anyRequest().authenticated()
        )
        .httpBasic(Customizer.withDefaults())   // or formLogin for a browser UI
        // actuator POSTs (e.g. /loggers) are not browser forms — exempt them from CSRF
        .csrf(csrf -> csrf.ignoringRequestMatchers(EndpointRequest.toAnyEndpoint()));
    return http.build();
}
```

![The filter chain: health permitAll, toAnyEndpoint hasRole ADMIN, swagger paths hasRole ADMIN, anyRequest your app rules — most-specific matcher first.](https://cdn.hashnode.com/uploads/covers/6a00c971e3eebc2e20b385b4/ffa70efc-6967-4916-b7e7-1b256e7e13f7.png align="center")

One thing the diagram is quietly insisting on: **order matters.** Spring Security takes the first matcher that matches, so the narrow `health` rule has to come *before* the broad `toAnyEndpoint()` — flip them and `toAnyEndpoint()` swallows health and your load balancer starts getting 401s. Most-specific first, every time.

And the credentials behind `ROLE_ADMIN` have to be real. Not the random password Boot prints to the console on startup, not `user` / `password` in a properties file. A proper user — from your database or directory — with a **BCrypt-hashed** secret:

```java
@Bean
PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
```

### Layer 4 — isolate the port

The last layer is network, not code. Move actuator off your public application port entirely:

```yaml
management:
  server:
    port: 9001          # actuator lives here...
    address: 127.0.0.1  # ...and only answers on loopback / your internal net
```

Now even a misconfigured rule upstream doesn't help an outside attacker, because the port they can reach doesn't serve actuator at all. Your monitoring, which lives on the same box or inside the same network, still gets in. This pairs naturally with a firewall or security group that simply never routes `9001` to the outside world.

## The short version

Swagger and Actuator aren't dangerous because they're insecure. They're dangerous because they're *useful*, which is exactly why you turned them on and then stopped seeing them. Treat them like any other privileged surface:

- **Expose less** — pin the actuator list, and turn Swagger off in prod unless you have a reason not to.
- **Authenticate** — put Spring Security in front of both.
- **Authorize** — `hasRole("ADMIN")`, not merely "logged in," with real BCrypt-backed credentials.
- **Isolate** — separate management port, bound to the internal network.

No single one of these is the answer. Stacked, they mean that the day one layer is misconfigured — and someday one will be — the other three are still standing between a stranger and a copy of your app's memory.
