Tzvi Gregory Kaidanov
Tzvi Gregory Kaidanov

Reputation: 3140

How to remove swagger production .net core 2.1

I have swagger working on multiple microservices. When deploying to Azure we need to remove all together the option of swagger due to security best practices. Working with .net core 2.1 Looking for example of definitions.

Upvotes: 23

Views: 36148

Answers (4)

user1007074
user1007074

Reputation: 2596

If you're coming at this from .net core 3.1:

Assuming that the Startup class' constructor copies the injected IConfiguration to a local field called configuration, then you can setup the Configure method like so:

public void configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    var applicationName = configuration.GetValue<string>("ApplicationName") ?? "MyApi";
    var basePath = configuration.GetValue<string>("BasePath");
    if (!string.IsNullOrEmpty(basePath))
        app.UsePathBase(basePath);

    if (!env.IsProduction())
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint($"{basePath}/swagger/v1/swagger.json",
                                $"{applicationName} {ReflectionUtils.GetAssemblyVersion<Program>()}");
        });
    }
}

Upvotes: 12

Martin.Martinsson
Martin.Martinsson

Reputation: 2154

First option, disabling it in Configure-method like:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // read from config
        var config = (IConfiguration)app.ApplicationServices.GetService(typeof(IConfiguration));

        enableSwagger = bool.Parse(config.GetValue<string>("EnableSwagger") ?? "false");

        if (enableSwagger /*|| env.IsDevelopment()*/)
        {
            app.UseSwagger(o =>
            {
                o.RouteTemplate = "swagger/{documentName}/swagger.json";
            });

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
        }
    }

or use:

if (env.IsDevelopment())
{
   ...
}

Second option is by completely removing all references and usings in code files by

#if USE_SWAGGER
using Microsoft.OpenApi.Models;
...
#endif

#if USE_SWAGGER
<some method>
...
#endif

add in .csproj:

<Choose>
  <When Condition="$(DefineConstants.Contains('USE_SWAGGER'))">
    <ItemGroup Condition="'$(TargetFramework)' == 'netstandard3.1'">
    <PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.6.3" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.6.3" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.6.3" />
    </ItemGroup>
  </When>
  <Otherwise />
</Choose>

or

<Choose>
  <When Condition="'$(Configuration)' == 'Debug'">
    <ItemGroup Condition="'$(TargetFramework)' == 'netstandard3.1'">
    <PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.6.3" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.6.3" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.6.3" />
    </ItemGroup>
  </When>
  <Otherwise />
</Choose>

Play around and you get profound!

Upvotes: 10

Felipe Torres
Felipe Torres

Reputation: 317

You could also use [ApiExplorerSettings(IgnoreApi = true)] in the controller classes you don't want to show in the documentation. This is an excludent action, meaning every class will be shown, except the ones marked with this attribute. (this is good when you want to make only a set of your APIs docs visible to a third-party consumer);

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239420

First, what "security best practices"? There's nothing wrong with having your API documentation in production. That's actually kind of the whole point: clients should be able to look at the documentation so that they can properly use your API. If these microservices aren't exposed to be used by external clients, then it's even less of an issue, because no one outside can get to the service or the documentation, anyways. If the services are exposed, then they should also be requiring requests to be authorized, and the documentation itself can be locked down via the same mechanism.

Regardless, if you insist on removing this in production, your best bet is to never add it there in the first place. In other words, wrap all your Swagger setup in Startup.cs with if (env.IsDevelopment()) or if you want it available in things like a staging environment: if (!env.IsProduction()).

Upvotes: 19

Related Questions