Asp.net-Web-Api

帶有花飾的標頭中的 API 密鑰

  • September 15, 2021

我想使用 Swashbuckle(.net 的招搖)對 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>)

它似乎創建了我期望的招搖文件:

“安全定義”:{
“apiKey”:{
“類型”:“apiKey”,
"description": "API 密鑰認證",
"name": "X-ApiKey",
“在”:“標題”
}
}

但是當我進入 UI 並“嘗試一下”時,它會嘗試將 API 密鑰放入查詢字元串(我認為這是預設行為)而不是標題中。

例如:

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

我怎樣才能大搖大擺地使用將 API 密鑰放在標頭而不是查詢字元串中?

2021 年 9 月 15 日更新:

正如 Justin Greywolf 的評論中已經指出的那樣。

“In”和“Type”屬性已從字元串更改為ParameterLocationSecuritySchemeType列舉:

services.AddSwaggerGen(c =&gt;{
   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 =&gt;{
   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 =&gt;
   {
       c.ApiKey("apiKey")
           .Description("API Key Authentication")
           .Name("X-ApiKey")
           .In("header");
       c.SingleApiVersion("v1", "My API");

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

引用自:https://stackoverflow.com/questions/36975389