asp.net-web-api - 带有 swashbuckle 的 header 中的 API key

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

我想使用 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/

相关文章:

c# - 对自定义 Web API AuthorizeAttribute 进行单元测试

asp.net - 向每个 swagger ui 请求添加 header

c# - WEB .NET 5 Newtonsoft 中的序列化 - 最后 2 位数字反序列化不正确

swagger - 如何在 nestjs 中禁用用于生产的 swagger

Springfox swagger-ui.html 无法推断基本 URL - 由缺少 cookie 引起

asp.net-web-api - 在 F# 中实现 IExceptionHandler 或 IExceptionLogger 等消息处理程序时,返回 "empty task"的正确方法是什么?

javascript - 从 WebAPI 获取 PDF 并从 UI 下载,但数据已损坏

c# - 具有全局 Web API 过滤器属性的 Unity 依赖注入(inject)

Swagger编辑器: ERROR Server not found or an error occurred

python - 将 2D 数组从 python 传递给 swagger