0

I want a way to affect on swagger output documentation. The issue is that user that asks docs can have permissions only to some of methods that described in swagger so I want to exclude specific methods from output. The worst approach I consider is catch swagger.json request by middleware and then just check what methods requested user has access to and exclude necessary paths. But I don't like it very much so may be there is built in feature to do that?

Artyom
  • 654
  • 2
  • 7
  • 16
  • I think this was already answered in [this topic](https://stackoverflow.com/questions/29701573/how-to-omit-methods-from-swagger-documentation-on-webapi-using-swashbuckle) – Krystian Sitek Nov 19 '19 at 09:05
  • No, it wasn't. In this topic some method/controller is excluded forever. But I need to exclude in runtime and for specific user omit specific methods. So firstly I check user's token and find him in database and then omit methods – Artyom Nov 19 '19 at 09:22

1 Answers1

0

Found an answer. Just need to create custom DocumentFilter that allows to edit output document:

public class RestrictSwaggerOperationsFilter : IDocumentFilter
{
    private readonly ILogger<RestrictSwaggerOperationsFilter> _logger;
    private readonly IHttpContextAccessor _contextAccessor; // inject service to get HttpContext with user claims
    private readonly IServiceScopeFactory _scope; // service for getting database context

    public RestrictSwaggerOperationsFilter(IHttpContextAccessor httpContextAccessor, IServiceScopeFactory scope, ILogger<RestrictSwaggerOperationsFilter> logger)
    {
        _contextAccessor = httpContextAccessor;
        _logger = logger;
        _scope = scope;
    }

    public void Apply(OpenApiDocument operation, DocumentFilterContext context)
    {
        using (var scope = _scope.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>();
            // do whatever check you need
            operation.Paths.Remove("key"); // removes specific path by key that represents path to a method
            // DocumentFilterContext contains ActionDescriptor for every API method
        }
    }
}

And then add this filter to ConfigureServices at Startup.cs:

services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            options.DocumentFilter<RestrictSwaggerOperationsFilter>();
        });

Works for Swashbuckle.AspNetCore version 5.0.0-rc4. For earlier versions I suppose there will be similar solution.

Artyom
  • 654
  • 2
  • 7
  • 16