You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swagger UI中记录ASP.NET MVC端点的授权属性与策略?

在Swagger UI中展示自定义授权属性与策略的实现方案

针对ASP.NET MVC + Swashbuckle.AspNetCore 6.3.1的场景,你可以通过自定义Swagger操作过滤器来读取端点上的自定义AuthorizeAttribute和授权策略,并将这些信息展示在Swagger UI中,具体实现如下:

1. 自定义Swagger操作过滤器

创建一个实现IOperationFilter的类,用于提取并格式化授权相关信息:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;

public class CustomAuthorizeOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var actionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
        if (actionDescriptor == null) return;

        // 获取当前端点(控制器+动作)上所有的AuthorizeAttribute(含自定义继承类)
        var authorizeAttributes = actionDescriptor.MethodInfo.GetCustomAttributes(true)
            .Union(actionDescriptor.ControllerTypeInfo.GetCustomAttributes(true))
            .OfType<AuthorizeAttribute>()
            .ToList();

        if (!authorizeAttributes.Any()) return;

        var authInfoBuilder = new System.Text.StringBuilder();

        // 提取自定义授权属性的类型与描述
        authInfoBuilder.AppendLine("**授权校验类型:**");
        foreach (var attr in authorizeAttributes.DistinctBy(a => a.GetType()))
        {
            // 如果自定义属性有Description字段,优先显示描述,否则显示类名
            var description = string.Empty;
            if (attr is PermissionCheckAttribute permAttr)
                description = permAttr.Description;
            else if (attr is CrossTenantCheckAttribute tenantAttr)
                description = tenantAttr.Description;
            else if (attr is ParameterCheckAttribute paramAttr)
                description = paramAttr.Description;
            else
                description = attr.GetType().Name.Replace("Attribute", "");

            authInfoBuilder.AppendLine($"- {description}");
        }

        // 提取关联的授权策略
        var policies = authorizeAttributes.Select(a => a.Policy)
            .Where(p => !string.IsNullOrEmpty(p))
            .Distinct();
        if (policies.Any())
        {
            authInfoBuilder.AppendLine("\n**绑定授权策略:**");
            foreach (var policy in policies)
            {
                authInfoBuilder.AppendLine($"- {policy}");
            }
        }

        // 将信息追加到Swagger端点的描述中
        operation.Description = string.IsNullOrEmpty(operation.Description)
            ? authInfoBuilder.ToString()
            : $"{operation.Description}\n\n{authInfoBuilder.ToString()}";
    }
}

2. 为自定义授权属性添加描述(可选)

如果希望展示更友好的说明,可以给自定义AuthorizeAttribute添加描述字段:

public class PermissionCheckAttribute : AuthorizeAttribute
{
    public string Description { get; set; } = "权限校验:验证用户是否拥有当前操作的执行权限";
}

public class CrossTenantCheckAttribute : AuthorizeAttribute
{
    public string Description { get; set; } = "跨租户校验:验证请求用户与资源所属租户匹配";
}

public class ParameterCheckAttribute : AuthorizeAttribute
{
    public string Description { get; set; } = "参数校验:验证请求参数与用户权限范围匹配";
}

3. 注册过滤器到SwaggerGen

在Program.cs(或Startup.cs)的Swagger配置中注册自定义过滤器:

builder.Services.AddSwaggerGen(c =>
{
    // 其他Swagger配置(如文档标题、版本等)
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的API文档", Version = "v1" });

    // 注册自定义授权过滤器
    c.OperationFilter<CustomAuthorizeOperationFilter>();
});

4. 效果说明

启动项目后,打开Swagger UI,每个带有自定义授权属性或策略的端点,其描述区域会显示对应的授权校验类型和绑定的策略信息,方便开发、测试人员快速了解端点的授权要求。

内容的提问来源于stack exchange,提问作者Kyoshiro Kokujou Obscuritas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:20:28