API 用 swashbuckle 输入 header

API key in header with swashbuckle

我想使用 Swashbuckle(.net 的 swagger)在 WebAPI 项目上进行 API 基于密钥的身份验证。

我已经配置了 swashbuckle 如下:

config
    .EnableSwagger(c =>
    {
        c.ApiKey("apiKey")
            .Description("API Key Authentication")
            .Name("X-ApiKey")
            .In("header");
        c.SingleApiVersion("v1", "My API");

    })
    .EnableSwaggerUi();

(参见 https://github.com/domaindrivendev/Swashbuckle#describing-securityauthorization-schemes

它似乎创建了我期望的 swagger 文件:

   "securityDefinitions": {
      "apiKey": {
        "type": "apiKey",
        "description": "API Key Authentication",
        "name": "X-ApiKey",
        "in": "header"
      }
    }

但是当我转到 UI 和 'Try it out' 时,它会尝试将 API 键放入查询字符串(我认为这是默认行为)而不是 headers.

例如:

curl -X POST --header 'Accept: application/json' 'http://localhost:63563/api/MyMethod?api_key=key'

我怎样才能大摇大摆地使用将 API 键放在 header 而不是查询字符串中?

您必须根据 original (as described here) 注入自定义 index.html 并更改函数中的以下行 addApiKeyAuthorization:

var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("X-ApiKey", key, "header");

2021-09-15 更新:

正如 Justin Greywolf 的评论中所述。

“In”和“Type”属性已从字符串更改为 ParameterLocationSecuritySchemeType 枚举:

services.AddSwaggerGen(c =>{
    c.SwaggerDoc("v1", new Info { Title = "[anything]", Version = "v1" });
    c.AddSecurityDefinition("[auth scheme: same name as defined for asp.net]", new ApiKeyScheme() {
        In = ParameterLocation.Header,
        Name = "X-API-KEY", //header with api key
        Type = SecuritySchemeType.ApiKey,
    });
});

2019-04-10 更新:

范式已转变为在生成的 swagger.json

中适应安全定义

来源https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements

services.AddSwaggerGen(c =>{
    c.SwaggerDoc("v1", new Info { Title = "[anything]", Version = "v1" });
    c.AddSecurityDefinition("[auth scheme: same name as defined for asp.net]", new ApiKeyScheme() {
        In = "header", // where to find apiKey, probably in a header
        Name = "X-API-KEY", //header with api key
        Type = "apiKey", // this value is always "apiKey"
    });

});

原答案

查看:

config
    .EnableSwagger(c =>
    {
        c.ApiKey("apiKey")
            .Description("API Key Authentication")
            .Name("X-ApiKey")
            .In("header");
        c.SingleApiVersion("v1", "My API");

    })
    .EnableSwaggerUi(c => {
        c.EnableApiKeySupport("X-ApiKey", "header");
    })