Apply claims-based authorization policy to Swagger UI in .Net Core 3.1

Viewed 906

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 Swagger UI to be accessible only to authorized users (i.e. not publicly available). I've read a lot of posts about how Swagger handles the API 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 [Authorize(Policy="MyCustomPolicy")] 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.

How is this claims requirement added to Swagger UI?

This is how I add the Swagger service:

// 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 =>
{
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "MySystem API",
            Version = "v1",
            Description = "API for MySystem.",
            Contact = new OpenApiContact
            {
                Name = "MyCompany S.A.",
                Email = string.Empty,
                Url = new System.Uri("https://contoso.com/"),
            },
        });

        var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "MySystem.Web.xml");
        c.IncludeXmlComments(filePath);

        c.CustomSchemaIds(x => x.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault()?.DisplayName ?? x.Name);
    });

This is how I add Swagger to my builder:

    // 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 =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MySystem API v1");

        // To serve SwaggerUI at application's root page, set the RoutePrefix property to an empty string.
        c.RoutePrefix = string.Empty;
    });

Thanks in advance.

1 Answers

It turns out that this was answered here. I've just had to add:

app.UseAuthentication(); // before UseAuthorization()

// Original answer
app.UseAuthorization(); // before the middleware
...

Related