Showing/hiding swagger UI endpoints based on API key

Viewed 412

I have swagger set up but it shows all the controllers for everyone. I'd like to only show controllers based on API key permissions, so they'll have to enter their API key in the Explore section of swagger to see anything. Is this do-able?

1 Answers

If we talk about Swashbuckle package then we need to use implement IDocumentFilter.

Some initial information you can review from this post.

Basic scenario:

  • Define custom Attribute
  • Setup this attribute to Controllers / Actions
  • Implement filtration logic in your DocumentFilter class

Code sample available here:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class LicenseValidatorAttribute : Attribute
{
    public FeatureType Feature { get; set; }
}

public class FeatureDocumentFilter : IDocumentFilter
{
    private readonly IFeatureService _featureService;

    public FeatureDocumentFilter(IFeatureService featureService)
    {
        _featureService = featureService;
    }

    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach (var api in context.ApiDescriptions)
        {
            var attribute = api.CustomAttributes().OfType<FeatureValidatorAttribute>().FirstOrDefault();

            if (attribute != null)
            {
                var success = _featureService.ValidateFeature(attribute.Feature);

                if (!success.Valid)
                {
                    var route = "/" + api.RelativePath;
                    swaggerDoc.Paths.Remove(route);
                }
            }
        }
    }
}
Related