【问题标题】:Add Authorize Attribute Filter in Swashbuckler Implementation of Swagger在 Swagger 的 Swashbuckler 实现中添加授权属性过滤器
【发布时间】:2019-02-15 01:19:55
【问题描述】:

希望将 AuthorizeFilterAttribute 或 AnonymousFilterAttribute 添加到 Swashbuckle 的 Swagger 实现中的端点,以便我可以查看在以 /swagger 结尾的正在运行的 webapi 中生成的文档文件中的每个端点上使用了哪个属性。这可能吗?

我特别想添加一个大粗体标签,说明此端点是 [Anonymous] 或该端点正在使用 [Authorize],并让它们看起来与摘要或备注文本不同。

我还希望能够为每个端点过滤掉所有不同类型的这些限制过滤器属性,包括 [NonAction]、[Authorize] 和 [Anonymous],其中一个可能位于每个控制器的顶部端点。甚至可能最终在每个端点上添加其他类型的 FilterAttributes。

目前看起来只有 HTTP 方法,请求和响应对象可以在当前实现中检索,所以我无法找到这方面的确切信息。

由于这是一个 Swagger 实现,这些 .NET 特定属性过滤器是否不会转换为 Swashbuckle b/c,它们仅实现 Swagger 规范中的内容,而不是其他内容?

最后是他们对 Swashbuckle 实现的 .NET 特定扩展吗?

谢谢!

【问题讨论】:

标签: swagger swashbuckle swashbuckle.examples


【解决方案1】:

对于将标签添加到不受保护的方法/操作的部分,您可以使用这样的操作过滤器

  public class UnprotectedOperationFilter : IOperationFilter
  {

    private bool HasAttribute(MethodInfo methodInfo, Type type, bool inherit)
    {
      // inhertit = true also checks inherited attributes
      var actionAttributes = methodInfo.GetCustomAttributes(inherit);
      var controllerAttributes = methodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes(inherit);
      var actionAndControllerAttributes = actionAttributes.Union(controllerAttributes);

      return actionAndControllerAttributes.Any(attr => attr.GetType() == type);
    }

    public void Apply(Operation operation, OperationFilterContext context)
    {

      bool hasAuthorizeAttribute = HasAttribute(context.MethodInfo, typeof(AuthorizeAttribute), true);
      bool hasAnonymousAttribute = HasAttribute(context.MethodInfo, typeof(AllowAnonymousAttribute), true);

      // so far as I understood the action/operation is public/unprotected 
      // if there is no authorize or an allow anonymous (allow anonymous overrides all authorize)
      bool isAuthorized = hasAuthorizeAttribute && !hasAnonymousAttribute;

      if (!isAuthorized)
      {
        operation.Description = 
          "<p><bold>BIG BOLD LABEL indicating an UPROTECTED PUBLIC method</bold></p>" 
          + operation.Description;
      }

    }
  }

并添加它

services.AddSwaggerGen(c => { c.OperationFilter<UnprotectedOperationFilter>();} );

我不明白你过滤掉不同属性的意思,但我希望上面的代码可以帮助你检查属性是否存在并做你想做的事情。

【讨论】:

  • 我注意到,当您使用 /swagger 打开服务时,您可以直接在右上角的 swashbuckler 搜索框中添加不记名令牌。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
相关资源
最近更新 更多