Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict access to certain API controllers in Swagger using Swashbuckle and ASP.NET Identity

So, I started using Swagger. I'm absolutely in love with it's features, but I have some doubts on availability of all methods to public.

As far as I understood - all included in Swaschbuclke "auth" methods are actually about APIs itself, but I don't need help there - all of my APIs are protected by API id/key pair.

I would like to somehow utilise ASP.NET Identity (login system) to restrict access to API page (/swagger/ui/index).

Is there any way? Any methods in Swaschbuckle? Any routes/Identity hacks?

Any help is appreciated.

Edit 1: [ApiExplorerSettings(IgnoreApi = true)] attribute is not what I'm looking for - it restricts all the access to the methods, regardless of Identity.

like image 830
Mike Neverov Avatar asked Oct 16 '15 17:10

Mike Neverov


1 Answers

Concerning restricting exposure of individual APIs in your swagger documentation:

Swashbuckle 5.x:

Swashbuckle 5.x has a configuration option called IgnoreObsoleteActions (that you need to set; it isn't enabled by default) that will hide actions if they have the [Obsolete] attribute.

Example: Configuration

httpConfiguration
    .EnableSwagger(c =>
        {
            c.IgnoreObsoleteActions();
        });

More info available in the documentation.

Swashbuckle 4.1.x (or if you don't want to use the obsolete attribute):

Swashbuckle builds the swagger documentation on top of IApiExplorer. You should be able to add an attribute -- [ApiExplorerSettings(IgnoreApi = true)] -- to manage ApiExplorerSettings the controller class or individual controller methods to have the explorer (and subsequently, Swashbuckle) ignore them when generating the documentation.

Example: Individual actions

/// Ignore 'GetFoo' in documentation
public class FooBarController
{
    [ApiExplorerSettings(IgnoreApi = true)]
    public Bar GetFoo
    {
       ...
    }

    public Bar GetBar
    {
       ...
    }
}

Example: Controller classes

/// Ignore every controller method in FooBarController in documentation
[ApiExplorerSettings(IgnoreApi = true)]
public class FooBarController
{
    public Bar GetFoo
    {
       ...
    }

    public Bar GetBar
    {
       ...
    }
}

More details in this GitHub Issue. I've used this myself in Swashbuckle 4.1.x.

like image 50
Anthony Neace Avatar answered Sep 19 '22 16:09

Anthony Neace