如何在Swagger UI中发送带有请求的自定义标头?

Ser*_*rov 56 api authorization swagger swagger-ui

我在API中有一些端点 - /user/login, /products.

在扬鞭UI我张贴email,并password/user/login和我收到的响应token串.

然后,我可以从响应中复制令牌,并希望将其用作Authorization对所有URL的请求中的标头值(如果它存在),并/products作为示例.

我应该在Swagger UI页面上的某处手动创建文本输入,然后将令牌放在那里并以某种方式注入请求或是否有工具以更好的方式管理它?

小智 48

在ASP.net WebApi上,在Swagger UI上传入标头的最简单方法是在IOperationFilter接口上实现Apply(...)方法.

将此添加到您的项目:

public class AddRequiredHeaderParameter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.parameters == null)
            operation.parameters = new List<Parameter>();

        operation.parameters.Add(new Parameter
        {
            name = "MyHeaderField",
            @in = "header",
            type = "string",
            description = "My header field",
            required = true
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

SwaggerConfig.cs上,使用c.OperationFilter <T>()注册上面的过滤器:

public static void Register()
{
    var thisAssembly = typeof(SwaggerConfig).Assembly;

    GlobalConfiguration.Configuration 
        .EnableSwagger(c =>
        {
            c.SingleApiVersion("v1", "YourProjectName");
            c.IgnoreObsoleteActions();
            c.UseFullTypeNameInSchemaIds();
            c.DescribeAllEnumsAsStrings();
            c.IncludeXmlComments(GetXmlCommentsPath());
            c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());


            c.OperationFilter<AddRequiredHeaderParameter>(); // Add this here
        })
        .EnableSwaggerUi(c =>
        {
            c.DocExpansion(DocExpansion.List);
        });
}
Run Code Online (Sandbox Code Playgroud)

  • @gee'K'iran 您可以通过检查操作和 apiDescription 参数并选择是否添加标题来选择性地应用该功能。 (3认同)
  • 您好,感谢分享,这正是我所需要的。有没有办法对某些 API 方法禁用它?例如,用户登录不需要在返回身份验证令牌时传递该标头。这会将“MyHeaderField”添加到所有 API 方法 Swagger 文档中。 (2认同)

Ted*_*ein 40

您可以在请求中添加标头参数,Swagger-UI会将其显示为可编辑的文本框:

swagger: "2.0"
info:
  version: 1.0.0
  title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http

paths:

  /taxFilings/{id}:

    get:
      parameters:
      - name: id
        in: path
        description: ID of the requested TaxFiling
        required: true
        type: string
      - name: auth
        in: header
        description: an authorization header
        required: true
        type: string
      responses:
        200:
          description: Successful response, with a representation of the Tax Filing.
          schema:
            $ref: "#/definitions/TaxFilingObject"
        404:
          description: The requested tax filing was not found.

definitions:
  TaxFilingObject:
    type: object
    description: An individual Tax Filing record.
    properties:
      filingID:
        type: string
      year:
        type: string
      period:
        type: integer
      currency:
        type: string
      taxpayer:
        type: object
Run Code Online (Sandbox Code Playgroud)

Swagger-UI与auth param文本框

您还可以添加类型为的安全性定义apiKey:

swagger: "2.0"
info:
  version: 1.0.0
  title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http

securityDefinitions:
  api_key:
    type: apiKey
    name: api_key
    in: header
    description: Requests should pass an api_key header.

security: 
 - api_key: []

paths:

  /taxFilings/{id}:

    get:
      parameters:
      - name: id
        in: path
        description: ID of the requested TaxFiling
        required: true
        type: string

      responses:
        200:
          description: Successful response, with a representation of the Tax Filing.
          schema:
            $ref: "#/definitions/TaxFilingObject"
        404:
          description: The requested tax filing was not found.

definitions:
  TaxFilingObject:
    type: object
    description: An individual Tax Filing record.
    properties:
      filingID:
        type: string
      year:
        type: string
      period:
        type: integer
      currency:
        type: string
      taxpayer:
        type: object
Run Code Online (Sandbox Code Playgroud)

securityDefinitions对象定义了安全方案.

security对象(在Swagger-OpenAPI中称为"安全性要求")将安全性方案应用于给定的上下文.在我们的例子中,我们通过将安全性要求声明为顶级来将其应用于整个API.我们可以选择在单个路径项和/或方法中覆盖它.

这将是指定安全方案的首选方式; 它取代了第一个例子中的header参数.不幸的是,Swagger-UI没有提供一个文本框来控制这个参数,至少在我的测试中到目前为止.


gpa*_*oli 19

ASP.NET Core 2 Web API,使用Swashbuckle.AspNetCore包2.1.0,实现一个IDocumentFilter:

SwaggerSecurityRequirementsDocumentFilter.cs

using System.Collections.Generic;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace api.infrastructure.filters
{
    public class SwaggerSecurityRequirementsDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument document, DocumentFilterContext context)
        {
            document.Security = new List<IDictionary<string, IEnumerable<string>>>()
            {
                new Dictionary<string, IEnumerable<string>>()
                {
                    { "Bearer", new string[]{ } },
                    { "Basic", new string[]{ } },
                }
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在Startup.cs中,配置安全性定义并注册自定义筛选器:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        // c.SwaggerDoc(.....

        c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
        {
            Description = "Authorization header using the Bearer scheme",
            Name = "Authorization",
            In = "header"
        });

        c.DocumentFilter<SwaggerSecurityRequirementsDocumentFilter>();
    });
}
Run Code Online (Sandbox Code Playgroud)

在Swagger UI中,单击"授权"按钮并设置令牌值.

窗口设置值

结果:

curl -X GET "http://localhost:5000/api/tenants" -H "accept: text/plain" -H "Authorization: Bearer ABCD123456"
Run Code Online (Sandbox Code Playgroud)


ben*_*_mj 18

这就是我在 .NET 6 中实现它的方法

public class AddCustomHeaderParameter 
    : IOperationFilter
{
    public void Apply(
        OpenApiOperation operation, 
        OperationFilterContext context)
    {
        if (operation.Parameters is null)
        {
            operation.Parameters = new List<OpenApiParameter>();
        }

        operation.Parameters.Add(new OpenApiParameter
        {
            Name = "Custom Header",
            In = ParameterLocation.Header,
            Description = "Custom Header description",
            Required = true,
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

最后

services.AddSwaggerGen(c =>
        {
            c.OperationFilter<AddCustomHeaderParameter>();
        });
Run Code Online (Sandbox Code Playgroud)


Vic*_*tov 12

此外,还可以将属性 [FromHeader] 用于应在自定义标头中发送的 Web 方法参数(或模型类中的属性)。像这样的东西:

[HttpGet]
public ActionResult Products([FromHeader(Name = "User-Identity")] string userIdentity)
Run Code Online (Sandbox Code Playgroud)

至少它适用于 ASP.NET Core 2.1 和 Swashbuckle.AspNetCore 2.5.0。


Vla*_*scu 5

这是 ASP.NET Core Web Api/Swashbuckle 组合的更简单的答案,不需要您注册任何自定义过滤器。第三次是一个魅力,你知道:)。

将下面的代码添加到您的 Swagger 配置中将导致出现“授权”按钮,允许您输入要为所有请求发送的不记名令牌。不要忘记按照Bearer <your token here>要求输入此令牌。

请注意,下面的代码将发送所有请求和操作的令牌,这可能是也可能不是您想要的。


    services.AddSwaggerGen(c =>
    {
        //...

        c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = "header",
            Type = "apiKey"
        });

        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
        {
            { "Bearer", new string[] { } }
        });

        //...
    }

Run Code Online (Sandbox Code Playgroud)

通过这个线程