title: Apply claims-based authorization policy to Swagger UI in .Net Core 3.1
body: <p>I've made an API using ASP.Net Core 3.1 and I've added Swagger UI at the root of the site using Swashbuckle. Maybe this is a trivial question, but I'd like the <strong>Swagger UI</strong> to be accessible only to authorized users (i.e. not publicly available). I've read a lot of posts about how Swagger handles the <em>API</em> authorization scheme, but none about the Swagger UI itself. In particular I need to restrict the access to the static files it creates through some <code>[Authorize(Policy=&quot;MyCustomPolicy&quot;)]</code> attribute or equivalent, so only users with a specific claim in their identity can access the UI. This condition is required only on the Swagger UI, because the API itself already has access control through Bearer authentication and that works just fine.</p>
  <p>How is this claims requirement added to Swagger UI?</p>
  <p>This is how I add the Swagger service:</p>
  <pre class="lang-cs prettyprint-override"><code>// Register the Swagger Generator service. This service is responsible for genrating Swagger Documents.
  // Note: Add this service at the end after AddMvc() or AddMvcCore().
  services.AddSwaggerGen(c =&gt;
  {
          c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo
          {
              Title = &quot;MySystem API&quot;,
              Version = &quot;v1&quot;,
              Description = &quot;API for MySystem.&quot;,
              Contact = new OpenApiContact
              {
                  Name = &quot;MyCompany S.A.&quot;,
                  Email = string.Empty,
                  Url = new System.Uri(&quot;https://contoso.com/&quot;),
              },
          });
  
          var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, &quot;MySystem.Web.xml&quot;);
          c.IncludeXmlComments(filePath);
  
          c.CustomSchemaIds(x =&gt; x.GetCustomAttributes(false).OfType&lt;DisplayNameAttribute&gt;().FirstOrDefault()?.DisplayName ?? x.Name);
      });
  </code></pre>
  <p>This is how I add Swagger to my builder:</p>
  <pre class="lang-cs prettyprint-override"><code>    // Enable middleware to serve generated Swagger as a JSON endpoint.
      app.UseSwagger();
  
      // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
      // specifying the Swagger JSON endpoint.
      app.UseSwaggerUI(c =&gt;
      {
          c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;MySystem API v1&quot;);
  
          // To serve SwaggerUI at application's root page, set the RoutePrefix property to an empty string.
          c.RoutePrefix = string.Empty;
      });
  </code></pre>
  <p>Thanks in advance.</p>