标题中的API密钥与swashbuckle

Not*_*ple 9 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();
Run Code Online (Sandbox Code Playgroud)

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

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

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

但是当我转到UI并"试一试"时,它会尝试将API密钥放入查询字符串(我认为是默认行为)而不是标题.

例如:

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

如何使用swigger将API密钥放在标头而不是查询字符串中?

Kei*_*ley 16

看看这个:

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"
    });
Run Code Online (Sandbox Code Playgroud)

  • @keith看起来在Swashbuckle 5.x中再次发生了变化,这又发生了变化。c.AddSecurityDefinition(“ ApiKey”,new OpenApiSecurityScheme {描述=“ ApiKey必须出现在标题中”,类型= SecuritySchemeType.ApiKey,名称=“ X-ApiKey”,在= ParameterLocation.Header}); (3认同)
  • 我还忘记使用 AddSecurityRequirement 添加安全要求,如下所述:https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements ,也许它可以帮助某人 (2认同)