标题中的API密钥与swashbuckle

时间:2016-05-02 05:14:49

标签: asp.net-web-api swagger swagger-ui swashbuckle

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

我已将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

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

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

但是当我进入用户界面并“试一试”时,它会尝试将API密钥放入查询字符串(我认为是默认行为)而不是标题。

例如:

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

如何使用标量的API键而不是查询字符串?

2 个答案:

答案 0 :(得分:13)

更新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");
    })

答案 1 :(得分:2)

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

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