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

.NET Core中如何在Swagger授权弹窗添加自定义参数

当然可以实现!针对你用的.NET + Swashbuckle(Swagger)场景,我整理了一套具体的方案,能帮你给授权弹窗添加自定义参数输入框,还能让这些参数顺利传递到你的ICustomTokenRequestValidator里做校验:

1. 配置Swagger OAuth2授权流程,声明自定义参数

首先在Program.cs(或Startup.cs)的SwaggerGen配置中,扩展OAuth2密码流的定义,明确告诉Swagger需要传递自定义参数:

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的API服务", Version = "v1" });

    // 配置OAuth2授权方案
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            Password = new OpenApiOAuthFlow
            {
                TokenUrl = new Uri("/connect/token", UriKind.Relative),
                Scopes = new Dictionary<string, string> { { "api", "API访问权限" } },
                // 关键:添加自定义参数的扩展声明
                Extensions = new Dictionary<string, IOpenApiExtension>
                {
                    {
                        "x-token-request-parameters",
                        new OpenApiObject
                        {
                            ["custom_param1"] = new OpenApiString(""),
                            ["custom_param2"] = new OpenApiString("")
                        }
                    }
                }
            }
        }
    });

    // 启用授权校验要求
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
            },
            new[] { "api" }
        }
    });
});
2. 自定义Swagger UI脚本,渲染额外输入框

上面的配置只是声明了参数,默认Swagger UI不会自动渲染这些自定义输入框,所以需要添加一段自定义JS来修改授权弹窗的表单:

先在SwaggerUI的配置中注入自定义脚本:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "你的API V1");
    c.OAuthClientId("你的客户端ID");
    c.OAuthAppName("你的API服务");

    // 注入自定义JS文件
    c.InjectJavascript("/swagger-custom.js");
});

然后在项目的wwwroot目录下创建swagger-custom.js文件,写入以下内容:

window.onload = function() {
    // 定位到密码授权的表单元素
    const passwordAuthForm = document.querySelector('.swagger-ui .oauth2-redirect-wrapper form[action*="/connect/token"]');
    if (!passwordAuthForm) return;

    // 添加第一个自定义参数输入框
    const param1Container = document.createElement('div');
    param1Container.className = 'input';
    param1Container.innerHTML = `
        <label for="custom_param1">自定义参数1</label>
        <input type="text" id="custom_param1" name="custom_param1" placeholder="请输入自定义参数1">
    `;
    passwordAuthForm.appendChild(param1Container);

    // 添加第二个自定义参数输入框
    const param2Container = document.createElement('div');
    param2Container.className = 'input';
    param2Container.innerHTML = `
        <label for="custom_param2">自定义参数2</label>
        <input type="text" id="custom_param2" name="custom_param2" placeholder="请输入自定义参数2">
    `;
    passwordAuthForm.appendChild(param2Container);
};
3. 在自定义令牌验证器中获取参数

当用户在Swagger授权弹窗填写自定义参数并提交时,这些参数会以form-data的形式和用户名、密码一起发送到/connect/token端点,你可以直接在ICustomTokenRequestValidator中获取并校验:

public class CustomTokenRequestValidator : ICustomTokenRequestValidator
{
    public Task ValidateAsync(CustomTokenRequestValidationContext context)
    {
        // 从请求原始数据中获取自定义参数
        if (context.Request.Raw.TryGetValue("custom_param1", out var param1Value))
        {
            // 执行你的校验逻辑
            if (string.IsNullOrWhiteSpace(param1Value))
            {
                context.Result = new TokenRequestValidationResult
                {
                    IsError = true,
                    Error = "自定义参数1不能为空"
                };
            }
        }

        return Task.CompletedTask;
    }
}
注意事项
  • 如果使用的是OAuth2的其他流程(比如隐式流),需要调整JS中的表单选择器,找到对应流程的授权表单。
  • 不同版本的Swagger UI可能DOM结构有差异,若JS无法定位到表单,需要根据实际页面结构修改选择器。
  • 确保swagger-custom.js的路径配置正确,能被Swagger UI加载到。

内容的提问来源于stack exchange,提问作者hahaha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 03:22:29