Security question on publishing OpenAPI documents and Swagger UI or Scalar in production: reconnaissance risk, leaked internal and admin endpoints, examples containing personal data, UI vulnerabilities and OAuth client settings, and the controls (environment gating, RequireAuthorization on MapOpenApi, separate public documents, API Management developer portals) plus when a public document is the right call.
Hiding the docs is not security: every endpoint must be protected by authentication and authorisation regardless. But publishing the full document hands an attacker a map: internal and admin endpoints, parameter names, limits, error shapes, sometimes examples with real personal data or OAuth client settings in the UI config.
My default for internal APIs is to map MapOpenApi() and the UI only in Development. If people need it in production, I put it behind RequireAuthorization("api-docs"), serve a separate curated document that excludes internal endpoints, or publish through an API Management developer portal.
For public or partner APIs a public document is the right call, as long as it's curated and the UI is patched. The trade-off: convenience for consumers versus cheaper reconnaissance.
"First, I'd separate two things people mix up. The document doesn't create vulnerabilities; an endpoint that's reachable without proper authorisation is vulnerable whether it's documented or not. So 'we hid Swagger' is never a security control. What the document does is make reconnaissance cheap: one request gives an attacker every path including admin and internal ones, every parameter name, validation limits, error formats and version numbers. I've also seen examples in specs containing real customer emails copied from production, and Swagger UI configs with an OAuth client secret in the page source.
So for an internal or line-of-business API my default is that the document and UI are mapped only when
IsDevelopment()is true, which is what the template does. If testers or another team need it in a deployed environment, I map it withRequireAuthorizationand anapi-docspolicy, and put the UI behind the same policy. Better still, I register a separate public document withShouldIncludethat leaves out anything under/internalor/admin. If the API sits behind Azure API Management, the developer portal is the right place: it handles sign-in and shows only the products a consumer is subscribed to.For example, at [company] a penetration test found the full spec of our [customer] API publicly reachable, including [12] admin endpoints. They were all protected, so there was no breach, but the report rated it as information disclosure and showed how it shortened their testing. I [gated the docs by environment, added a curated partner document behind authentication, and scrubbed examples]. For a genuinely public API, though, a public document is a feature: then I curate it, keep Swagger UI or Scalar patched, and make sure examples are synthetic, because under APP 11 personal information in a published spec is still a disclosure. The mistake I see is treating docs exposure as either harmless or as the security boundary. It's neither."
| Exposure | Why it matters |
|---|---|
| Internal, admin, debug endpoints | Targets for broken access control testing (OWASP API1, API5) |
| Parameter names, types, limits | Faster fuzzing and mass-assignment attempts |
| Error shapes, versions | Fingerprinting of frameworks and libraries |
| Examples | Can contain real personal data or tokens copied from logs |
| UI OAuth config | Client IDs, sometimes secrets, redirect URIs |
| UI itself | Another web app to patch; old Swagger UI versions had issues with loading remote specs via query parameters |
| Control | How in ASP.NET Core | Fit |
|---|---|---|
| Development only | if (app.Environment.IsDevelopment()) app.MapOpenApi(); |
Default for internal APIs |
| Authenticated docs | app.MapOpenApi().RequireAuthorization("api-docs") |
Testers, internal consumers |
| Curated public document | Second AddOpenApi("public") with ShouldInclude |
Partners, public APIs |
| Developer portal | Azure API Management imports the spec | Many external consumers, subscriptions |
| Network restriction | Private endpoint, internal ingress only | Internal platforms |
| Static file from CI | Publish the committed spec to a docs site | Public docs without a live endpoint |
After a pen test flagged our public spec, we moved the full document to Development only, published a curated partner document behind Entra ID sign-in, and replaced [40] examples with synthetic data. Requests to /openapi from unknown IPs dropped from [several thousand] a week to zero, and the next pen test had no information disclosure finding.
Checks whether the candidate can reason about information disclosure without confusing it with access control, and can propose proportionate controls.
Green flags
RequireAuthorization on MapOpenApi, curated documents or a developer portal.Red flags
Attacker
|
| GET /openapi/v1.json (one request, full API map)
v
API ----> paths: /orders, /admin/users, /internal/reindex, /debug/config
params, limits, error shapes, examples
|
+--> targeted tests: BOLA on /orders/{id}, admin endpoints without roles,
mass assignment using documented property names
The vulnerabilities (broken object level authorisation, broken function level authorisation, mass assignment) exist without the document. The document reduces attacker effort from hours of crawling and guessing to minutes. So the right framing is defence in depth: secure endpoints first, then reduce information disclosure.
The .NET 9+ web API template maps the document inside if (app.Environment.IsDevelopment()). Problems start when someone moves it outside "to help the front-end team" and the change ships to production, or when the environment variable isn't set and the app runs as Production while a developer assumed Development (the safe default works in your favour here).
MapOpenApi() returns an IEndpointConventionBuilder, so normal endpoint conventions apply: RequireAuthorization, RequireHost, CacheOutput. A UI served by Scalar or Swagger UI middleware must be protected the same way; otherwise the UI loads but the document request fails, which is acceptable, or worse, the UI is configured to fetch a public copy.
Browser-based docs need a login flow. Use authorisation code with PKCE and a public client registration for the UI. Never embed a client secret in UI configuration: it is sent to every browser.
AddOpenApi("internal") -> everything, Development or authenticated
AddOpenApi("public", o => o.ShouldInclude = d =>
!d.RelativePath!.StartsWith("admin") && !d.RelativePath.StartsWith("internal"))
A curated document is also a design tool: if you can't explain an endpoint to a partner, maybe it shouldn't be on the same host.
Examples and descriptions are published content. If they contain personal information (names, emails, Medicare numbers copied from a support ticket), that is a disclosure under the Privacy Act 1988, and APP 11 requires reasonable steps to protect it. Use clearly synthetic examples. The ACSC's guidance on hardening internet-facing services points the same way: minimise what you expose.
ASPNETCORE_ENVIRONMENT=Production and confirm /openapi/v1.json returns 404..RequireAuthorization("api-docs") to MapOpenApi() and call it anonymously and with a token.public document with ShouldInclude and diff it with the full one.@, digits that look like phone numbers or real names in examples.Gated docs: full document in Development, a curated authenticated document elsewhere.
// Program.cs
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorizationBuilder()
.AddPolicy("api-docs", p => p.RequireAuthenticatedUser().RequireRole("ApiConsumer", "Developer"));
builder.Services.AddOpenApi("internal"); // everything
builder.Services.AddOpenApi("partner", o =>
{
// curated: nothing under /admin or /internal is described to partners
o.ShouldInclude = d => d.RelativePath is { } p
&& !p.StartsWith("admin", StringComparison.OrdinalIgnoreCase)
&& !p.StartsWith("internal", StringComparison.OrdinalIgnoreCase);
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi(); // /openapi/internal.json and /openapi/partner.json, no auth locally
app.MapScalarApiReference();
}
else
{
// only the curated document, only for signed-in consumers, cached because it rarely changes
app.MapOpenApi("/openapi/partner.json")
.RequireAuthorization("api-docs")
.CacheOutput();
}
app.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new { id })).RequireAuthorization();
app.MapPost("/admin/reindex", () => TypedResults.Accepted("/admin/reindex/status")).RequireAuthorization("admin");
app.Run();
// Tests/DocsExposureTests.cs: the production configuration must not leak docs
using System.Net;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
namespace Orders.Api.Tests;
public sealed class DocsExposureTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
[Theory]
[InlineData("/openapi/internal.json", HttpStatusCode.NotFound)]
[InlineData("/openapi/partner.json", HttpStatusCode.Unauthorized)]
[InlineData("/scalar/internal", HttpStatusCode.NotFound)]
public async Task Docs_are_gated_in_production(string path, HttpStatusCode expected)
{
var client = factory.WithWebHostBuilder(b => b.UseEnvironment("Production")).CreateClient();
var response = await client.GetAsync(path, TestContext.Current.CancellationToken);
Assert.Equal(expected, response.StatusCode);
}
}
MapOpenApi() outside the IsDevelopment() block "temporarily". Why it is wrong: It ships to every environment, including production and pre-production environments holding real data, and publishes the full internal document, admin endpoints and examples to anyone who asks. Instead: Use an authenticated mapping or a feature flag, and a test that asserts production behaviour.ShouldInclude./openapi* and /swagger* (WAF, Front Door or Application Insights requests table) and on 401/403 spikes for admin routes.The senior answer avoids both extremes. Docs exposure isn't a vulnerability by itself, and hiding them doesn't make insecure endpoints safe; but there's also no reason to give attackers a free map of an internal API, because a map turns a weak authorisation check from "might be found" into "will be found this afternoon". I decide by audience: internal APIs keep docs in Development or behind authentication; partner APIs get a curated, authenticated document or an API Management portal; public APIs get a curated public document as part of the product. In every case, endpoints are secured independently, a test asserts what production exposes, and monitoring confirms it stays that way: a KQL alert on anonymous requests to docs paths, and on bursts of 401/403 against /admin routes, which is what reconnaissance looks like.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Development only | Internal APIs | Deployed testers need another route | Public or partner APIs |
| Authenticated docs endpoint | Internal consumers, testers | Login flow for the UI | Anonymous public consumers |
| Curated partner/public document | External consumers | Maintain inclusion rules | Single internal consumer |
| API Management developer portal | Many external consumers, subscriptions | APIM cost and setup | Small internal services |
| Static docs site from CI | Public docs without a live endpoint | Publishing pipeline | When docs must reflect each deployed environment |
OpenAPI is the vendor-neutral specification for describing HTTP APIs (paths, operations, schemas, security), currently 3.0 and 3.1. Swagger was the original name of that spec up to 2.0 and is now SmartBear's tooling brand (Swagger UI, Swagger Editor). In ASP.NET Core two jobs are separate: a generator builds the OpenAPI document from your endpoints, and a viewer renders it.
Microsoft.AspNetCore.OpenApi (AddOpenApi, MapOpenApi) instead of Swashbuckle, and ship no UI.The trade-off: the built-in generator is first-party and AOT-friendly, while Swashbuckle and NSwag have more mature extensions and, for NSwag, client generation.
You register a document with builder.Services.AddOpenApi("v1", o => ...) and serve it with app.MapOpenApi(), which maps /openapi/v1.json (a .yaml route also works in .NET 10). Customisation happens in transformers:
Info, servers, security schemes.For JWT you add a bearer scheme to Components.SecuritySchemes and a requirement on operations that have IAuthorizeData metadata. In .NET 10 the output is OpenAPI 3.1 by default (JSON Schema 2020-12, nullability as type arrays) on Microsoft.OpenApi 2.x, so some .NET 9 transformer code needs updating. The trade-off: transformers are explicit and AOT-friendly but you write the plumbing Swashbuckle filters used to give you.
How to tell it (STAR)
**S:** A pen test at [company] found our full API spec and Swagger UI public, including [12] admin endpoints and examples with what looked like real customer emails. **T:** I owned the fix and the assessment of whether any personal information had been disclosed. **A:** I confirmed the admin endpoints were properly protected, gated the docs by environment the same day, removed and traced the real examples, worked with our privacy officer on the NDB assessment, and replaced public docs with a curated, authenticated partner document plus a test that checks production exposure. **R:** The retest closed the finding, anonymous requests to the docs dropped to [zero], and the spec scan has since caught [2] more examples with personal data before release.
Last updated 23 Nov 2026.