【问题标题】:Swagger output filteringSwagger 输出过滤
【发布时间】:2019-11-20 19:17:26
【问题描述】:

我想要一种影响大张旗鼓输出文档的方法。问题是询问文档的用户只能对 swagger 中描述的某些方法拥有权限,因此我想从输出中排除特定方法。我认为最糟糕的方法是通过中间件捕获 swagger.json 请求,然后检查请求的用户可以访问哪些方法并排除必要的路径。但是我不太喜欢它,所以可能有内置功能可以做到这一点?

【问题讨论】:

  • 我认为this topic已经回答了这个问题
  • 不,不是。在本主题中,某些方法/控制器被永远排除在外。但我需要在运行时排除特定用户并省略特定方法。所以首先我检查用户的令牌并在数据库中找到他然后省略方法

标签: swagger asp.net-core-webapi


【解决方案1】:

找到了答案。只需要创建允许编辑输出文档的自定义 DocumentFilter:

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
        }
    }
}

然后将此过滤器添加到ConfigureServicesStartup.cs

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

适用于 Swashbuckle.AspNetCore 版本 5.0.0-rc4。对于早期版本,我想会有类似的解决方案。

【讨论】: