📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Should Swagger UI or the OpenAPI document be exposed in production? Explain the risks, how you would secure or environment-gate the docs, and when a public document is the right call.

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.

Senior Security Advanced api-management aspnet-core openapi privacy-act security swagger-ui

🎯 Key points

  • Hiding docs is not access control: every endpoint must be secured on its own; the document doesn't create vulnerabilities but makes existing ones far cheaper to find and exploit
  • Risks: full map of internal, admin and debug endpoints, parameter names and validation limits, error shapes, versions; examples with real personal data; UI vulnerabilities and OAuth client settings exposed
  • Default for internal APIs: map the document and UI only in Development (what the .NET 9+ template does); for deployed environments, gate with authorisation rather than removing the check
  • If needed outside Development: MapOpenApi().RequireAuthorization("api-docs") and the same policy on the UI, or serve from an internal network or APIM developer portal
  • Publish a separate curated document (ShouldInclude) that excludes internal and admin endpoints instead of exposing the full one
  • Never put client secrets in Swagger UI OAuth config; use authorisation code with PKCE and a public client
  • Monitor docs access: alert on anonymous requests to /openapi or /swagger paths and on 401/403 spikes against documented admin endpoints
  • Public or partner APIs benefit from a public document: then curate it, review examples for PII (Privacy Act APP 11) and keep the UI patched

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 with RequireAuthorization and an api-docs policy, and put the UI behind the same policy. Better still, I register a separate public document with ShouldInclude that leaves out anything under /internal or /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."


What an exposed document reveals

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

Controls

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can reason about information disclosure without confusing it with access control, and can propose proportionate controls.

Green flags

  • States clearly that hiding docs is not access control.
  • Names concrete risks: admin endpoints, examples with personal data, OAuth config.
  • Uses environment gating, RequireAuthorization on MapOpenApi, curated documents or a developer portal.
  • Recognises when a public document is right.

Red flags

  • "Swagger in production is fine, everything's behind auth anyway" with no nuance.
  • Believes hiding docs secures the API.
  • Puts client secrets in UI config.

📚 Learn in depth

1. Threat model

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.

2. What the template does

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).

3. Protecting the endpoints

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.

4. Curated documents

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.

5. Australian context

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.

Try it yourself

  1. Run your API with ASPNETCORE_ENVIRONMENT=Production and confirm /openapi/v1.json returns 404.
  2. Add .RequireAuthorization("api-docs") to MapOpenApi() and call it anonymously and with a token.
  3. Register a public document with ShouldInclude and diff it with the full one.
  4. Search your spec for @, digits that look like phone numbers or real names in examples.
  5. View the page source of your docs UI and check what OAuth settings it exposes.

💻 Code

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);
    }
}

⚠ Common mistakes

  • Mistake: Treating hidden docs as a security control. Why it is wrong: Attackers can crawl, guess or read the front-end bundle; endpoints must be protected regardless. Instead: Secure every endpoint with authorisation; treat doc gating as defence in depth.
  • Mistake: Moving 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.
  • Mistake: Exposing the full internal document to partners. Why it is wrong: It reveals admin and internal endpoints they never need. Instead: Publish a curated document with ShouldInclude.
  • Mistake: Putting an OAuth client secret in Swagger UI configuration. Why it is wrong: It is sent to every browser. Instead: Authorisation code with PKCE and a public client.
  • Mistake: Copying real request payloads into examples. Why it is wrong: Published personal information is a disclosure under the Privacy Act (APP 11). Instead: Synthetic examples, reviewed like code.
  • Mistake: Protecting the document but not the UI, or the reverse. Why it is wrong: The UI may load a public copy, or show a broken page that leaks configuration. Instead: Apply the same policy to both.
  • Mistake: Applying controls and never checking them. Why it is wrong: A later change can quietly re-expose the docs, and you won't see reconnaissance against your admin endpoints. Instead: Alert on anonymous hits to /openapi* and /swagger* (WAF, Front Door or Application Insights requests table) and on 401/403 spikes for admin routes.
  • Mistake: Leaving the docs UI package unpatched. Why it is wrong: It's a web app with its own vulnerabilities. Instead: Keep it in dependency scanning and update it with the rest.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about protecting both the document and the UI. Why: Checks the basics of the document versus the UI being gated.
    How to answer

    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.

    • Since .NET 9 the templates use Microsoft's own Microsoft.AspNetCore.OpenApi (AddOpenApi, MapOpenApi) instead of Swashbuckle, and ship no UI.
    • In .NET 10 it emits OpenAPI 3.1 by default.
    • Swagger UI or Scalar are optional viewers you add yourself.

    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.

  2. When: Candidate proposes a curated public document. Why: Checks how multiple documents and security schemes are configured.
    How to answer

    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:

    • Document transformers change the whole document: Info, servers, security schemes.
    • Operation transformers change one operation: add a security requirement or a header.
    • Schema transformers change the schema of one type: formats, examples.

    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.

🛠 Real-world problems: how you handle them

Pen test finds the full API spec, including admin endpoints, publicly reachable
Situation
A [customer portal] API on .NET 10 in Azure App Service, Australia East, handling personal information for [200k] customers. Annual penetration test before a [government] contract renewal.
Signals
Pen test report rated "information disclosure: full OpenAPI document and Swagger UI publicly accessible" as medium; the document listed [12] `/admin` endpoints and contained examples with what looked like real customer emails; WAF logs showed regular anonymous requests to `/swagger/v1/swagger.json`.
Investigation
Checked `Program.cs` history and found `UseSwagger()`/`UseSwaggerUI()` moved outside the Development check [a year earlier] for a front-end team; confirmed with the pen testers that every admin endpoint correctly returned 403; searched the spec for examples and traced [3] to a support ticket copied into XML comments; checked the UI config for OAuth settings.
Resolution
Same day: gated the docs by environment and redeployed, removed the real examples and assessed whether the exposure was an eligible data breach under the NDB scheme with the privacy officer. Then added a curated partner document behind Entra ID authentication, migrated from Swashbuckle to the built-in generator, and moved the UI to Scalar with PKCE.
Prevention
A `WebApplicationFactory` test asserting docs return 404 or 401 in Production; a CI check that scans the spec for email and phone patterns; docs exposure added to the security review checklist; pen test retest confirmed closure.

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.

↩ Usually asked after

More in API Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me