我想使用 Swashbuckle (swagger for .net) 对 WebAPI 项目进行基于 API key 的身份验证。
我已将 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 文件:
“安全定义”:{
“apiKey”:{
"type": "apiKey",
"description": "API key 认证",
"name": "X-ApiKey",
“在”:“标题”
}
}
但是当我进入 UI 并“尝试一下”时,它会尝试将 API key 放入查询字符串(我认为这是默认行为)而不是标题中。
例如:
curl -X POST --header 'Accept: application/json' 'http://localhost:63563/api/MyMethod?api_key=key'
如何让 swagger 使用将 API key 放在标题中而不是查询字符串中?
最佳答案
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");
})
关于asp.net-web-api - 带有 swashbuckle 的 header 中的 API key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36975389/