【问题标题】:Is there a way to document how an endpoint is protected using swaggerUI?有没有办法记录如何使用 swaggerUI 保护端点?
【发布时间】:2023-01-27 18:11:23
【问题描述】:

嘿嘿! 我有一个相当大的应用程序,其中包含一些端点和授权方案。 为了保护它们,我为权限、不同租户中的权限和参数创建了 3 个 AuthorizeAttributes,以便在访问端点本身之前检查它们。还有更多。 我还创建了授权策略,例如用户需要在请求的用户属性中列出。

现在,如果我们的 swagger UI 可以列出适用于端点的那些属性和策略,那么对于测试、记录和开发将非常有帮助。有什么办法吗?

作为一个框架,我使用微软 MVC,所以控制器都继承自 Microsoft.AspNetCore.Mvc.ControllerBase

至于我正在使用的 swagger 包: Swashbuckle.AspNetCore.Swagger 版本 6.3.1。 (SwaggerGen/SwaggerUi)

【问题讨论】:

  • 什么是网络框架?你能举一个最小的例子吗?
  • 编辑问题以包含该信息

标签: c# .net swagger


【解决方案1】:

假设使用 ASP.NET Core 和 Swashbuckle,您可以使用 MarkupFilter 在 Swagger UI 中提供附加信息:

using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Tool
{
    internal class AuthorizationMarkupFilter : IOperationFilter
    {
        private static ImmutableHashSet<string> GetPolicies(MethodInfo methodInfo)
        {
            var actionAttributes = methodInfo.GetCustomAttributes<AuthorizeAttribute>(true);
            var controllerAttributes = methodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes<AuthorizeAttribute>(true);

            var result = ImmutableHashSet<string>.Empty;

            foreach (var attribute in actionAttributes.Union(controllerAttributes))
            {
                if (!string.IsNullOrWhiteSpace(attribute.Policy))
                {
                    result = result.Add(attribute.Policy);
                }
            }

            return result;
        }

        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var policies = GetPolicies(context.MethodInfo);

            if (policies.Count > 0)
            {
                var sb = new StringBuilder();
                sb.AppendLine("<div>");
                sb.AppendLine("<b>Authorization:</b>");
                sb.AppendLine("<ul>");
                foreach (string policy in policies.OrderBy(s => s))
                {
                    sb.Append("<li>").Append(HttpUtility.HtmlEncode(policy)).AppendLine("</li>");
                }
                sb.AppendLine("</ul>");
                sb.AppendLine("</div>");

                operation.Description += sb.ToString();
            }
        }
    }
}

然后在你的“启动”类中:

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

我已经从一些更大的解决方案中删除了它,所以我希望它能编译。但我希望你明白了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-27
    • 2020-12-10
    • 2020-04-02
    • 2021-06-17
    • 2019-02-25
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多