我想在一个带有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密钥放在标头而不是查询字符串中?
我有一个 .NET Core 2.x 项目,它集成了 Swagger 和 Swashbuckle v4.x。这一切都运作得非常好。
但是,现在我需要以 www.foo.com/myendpoint? 的形式向 Swagger 触发的每个 GET 附加一个查询字符串?authorization=APIKEY。为此,我在 Startup.ConfigureServices 中有以下内容:
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.AddSecurityDefinition("api key", new ApiKeyScheme() {
Description = "Authorization query string expects API key",
In = "query",
Name = "authorization",
Type = "apiKey"
});
});
Run Code Online (Sandbox Code Playgroud)
当我启动 swagger 时,它确实会向我显示一个对话框,并在我输入 API 密钥时成功接受它。但是,所有 API 调用仍然会在没有查询字符串的情况下发出。
我缺少什么?