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?
If we talk about Swashbuckle package then we need to use implement IDocumentFilter
.
Some initial information you can review from this post .
Basic scenario:
Attribute
Controllers
/ Actions
DocumentFilter
classCode 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);
}
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.