【问题标题】:How to send Authorization header with a request in Swagger UI?如何在 Swagger UI 中发送带有请求的授权标头?
【发布时间】:2015-08-01 18:14:36
【问题描述】:

我有一个 ASP.NET Web Api 2 应用程序。我在其中添加了 Swashbuckle(Swagger for .NET)。它显示我的端点没有问题,但为了发送请求,我需要将 Authorization 标头附加到该请求。如果我理解正确,我需要修改 index.html 文件 (https://github.com/swagger-api/swagger-ui#how-to-use-it),所以我 git 克隆了 Swashbuckle 项目以修改 index.html 并添加一些标题。

这是在 Swashbuckle 中随请求发送 Authorization 标头的唯一方法吗?

【问题讨论】:

  • @AlbertoPellizzon - 我将在哪里添加该代码?什么文件?
  • 在 swaggerUi 初始化后尝试搜索初始化位置,例如 var swaggerUi = new SwaggerUi({});
  • 我的代码中没有类似的东西。我有: GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "MyApplication"); }) .EnableSwaggerUi(c => {}));在 SwaggerConfig.cs 中
  • 对,看来我必须修改包含一些 javascript 的 index.html。当我把它完全排序后,我会回答这个问题。

标签: swagger swagger-ui swashbuckle swagger-2.0


【解决方案1】:

我认为通过修改index.html来发送授权头不是一个好方法。您只能添加一些设置来实现这一点。
这是我的解决方案:
1.在Starup.cs ConfigureServices方法中添加设置

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerGen(config => {
            config.SwaggerDoc("v1", new OpenApiInfo() { Title = "WebAPI", Version = "v1" });
            config.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey,
                Scheme = "Bearer"
            });
            config.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    Array.Empty<string>()
                }
            });
        });
    }

2.在Startup.cs 配置方法中添加设置

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Document"));
    }

添加设置后,再运行这个项目,可以找到一个授权按钮 swagger page,可以用来设置授权头。

【讨论】:

    【解决方案2】:

    对于不记名令牌,我是这样做的: 我只使用 swashbuckle 来生成 swagger.json 文件,并使用 Swagger.Net 来显示最新的 SwaggerUI 版本(3.xx)并对其进行自定义:

    所以在我的项目参考中,我添加了(通过 nuget):

    在 index.html 中:

    <input id="bearer-code-input" type="text" placeholder="Enter Bearer Token here" style="width: auto" value="yourtoken" />
    

    然后在 SwaggerUIBundle 构造函数中:

    const ui = SwaggerUIBundle({
    ...,
    requestInterceptor: function (req) {
    req.headers = {
    'Authorization': 'Bearer ' + document.getElementById('bearer-code-
    input').value
    , 'Accept': 'application/json',
    'Content-Type': 'application/json'
    };
    return req;
    },
    ... })
    

    结果展示:

    我还定制了很多其他功能(Json 模型绑定器、查询字符串解析、自定义 SwaggerGenerator 以覆盖 ConflictingActionsResolver 的默认行为以能够处理多个路由路径,但不在本线程的范围内)

    【讨论】:

      【解决方案3】:

      我在 js 文件中添加了以下代码,并将其作为嵌入式资源添加到我的 web api 项目中。当您构建并运行 Swagger 时,api_key 文本框将被替换为授权密钥文本框,您可以在其中粘贴您的 AuthKey,并且对于每个请求,swagger 都会将其添加到请求标头中。

      (function () {
      
          $(function () {
              var basicAuthUI =
               '<div class="input"><input placeholder="Authorization Token" id="input_token" name="token" type="text"></div>';
                  $(basicAuthUI).insertBefore('#api_selector div.input:last-child');
                  $("#input_apiKey").hide();
                  $('#input_token').change(addAuthorization);
          });
      
          function addAuthorization() {
              var token = $('#input_token').val();
      
              if (token && token.trim() !== "" ) {
                  window.swaggerUi.api.clientAuthorizations.add("api_key", new window.SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + token, "header"));
                  console.log("authorization added: Bearer = " + token);
              }
          }
      
      })();
      

      【讨论】:

        【解决方案4】:

        为了使用 Swagger UI 发送带有请求的授权标头,我需要:

        1. 鉴于我的程序集的名称是:My.Assembly,它包含一个文件夹:Swagger, 在我放置自定义 index.html 的位置,我在 SwaggerConfig.cs 中添加了这一行:

           c.CustomAsset("index", thisAssembly, "My.Assembly.Swagger.index.html");
          

        请注意,index.html 会加载 javascript 和 css 文件。为了加载这些文件,我必须将文件路径中的所有点都更改为虚线。不知道为什么要这么做,但是它解决了加载文件的问题...

        1. 在 index.html 文件中我修改了

          addApiKeyAuthorization()

        函数看起来像这样:

        function addApiKeyAuthorization() {
                var key = encodeURIComponent($('#input_apiKey')[0].value);
                if (key && key.trim() != "") {
                    var value = "auth-scheme api_key=123456,order_id=56789";
                    var authKeyHeader = new SwaggerClient.ApiKeyAuthorization("Authorization", value, "header");
                    window.swaggerUi.api.clientAuthorizations.add("Authorization", authKeyHeader);
                }
            }
        

        请注意,我将“查询”更改为“标题”。

        1. 我也取消了这段代码的注释:

          var apiKey = "this field represents header but can be anything as long as its not empty";
          $('#input_apiKey').val(apiKey);
          

        它将在第二个文本字段中显示文本,但它似乎并不重要,只要它不为空。

        这对我有用,使我能够加载自定义 index.html 文件。现在我正在研究让 Swagger UI 用户能够操纵标头参数的值...

        【讨论】:

        • 它对我也不起作用,没有错误。你在哪里调用 addApiKeyAuthorization?
        最近更新 更多