title: How to protect swagger endpoint in .NET Core API?
body: <p>I have an api build in .net core 2.1. To restrict access to various endpoints, I use IdentityServer4 and [Authorize] attribute. However, my goal during development is to expose the api swagger documentation to our developers so that they may use it no matter where they work from. The challenge that I face is how do I protect the swagger index.html file so that only they can see the details of the api.</p>
  
  <p>I have created a custom index.html file in the wwwroot/swagger/ui folder and that all works, however, that file uses data from <code>/swagger/v1/swagger.json</code> endpoint which is not protected. I would like to know how can I override the return value for that specific endpoint so that I may add my own authentication to it?</p>
  
  <p>EDIT:</p>
  
  <p>Currently, I have achieved the above with the following middleware:</p>
  
  <pre><code>public class SwaggerInterceptor
  {
      private readonly RequestDelegate _next;
  
      public SwaggerInterceptor(RequestDelegate next)
      {
          _next = next;
      }
  
      public async Task Invoke(HttpContext context)
      {
          var uri = context.Request.Path.ToString();
          if (uri.StartsWith("/swagger/ui/index.html"))
          {
              var param = context.Request.QueryString.Value;
  
              if (!param.Equals("?key=123"))
              {
                  context.Response.StatusCode = 404;
                  context.Response.ContentType = "application/json";
                  await context.Response.WriteAsync("{\"result:\" \"Not Found\"}", Encoding.UTF8);
                  return;
              }
          }
  
          await _next.Invoke(context);
      }
  }
  
  public class Startup 
  {
      //omitted code
  
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
          app.UseMiddleware&lt;SwaggerInterceptor&gt;();
          //omitted code
      }
  }
  </code></pre>
  
  <p>What I don't like about this approach as it will inspect every single request. Is there a better way to achieve this? The above only protects the index.html file, but I can adjust it to protect the json endpoint in the similar fashion.</p>