带Swashbuckle的标头中的API密钥 [英] API key in header with swashbuckle

查看:107
本文介绍了带Swashbuckle的标头中的API密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Swashbuckle(适用于.net的swagger)对WebAPI项目进行基于API密钥的身份验证.

I want to do API key based authentication on a WebAPI project with Swashbuckle (swagger for .net).

我已经配置了swashbuckle,如下所示:

I have configured swashbuckle as below:

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-方案)

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

It appears to create the swagger file I expect:


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

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

But when I go to the UI and 'Try it out' it tries to put the API key into the query string (which I think is the default behavior) instead of the headers.

例如:

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

如何大张旗鼓地使用API​​密钥而不是查询字符串?

推荐答案

更新2019-04-10:

范式已转变为在生成的swagger.json中容纳安全性定义

Update 2019-04-10:

The paradigm has shifted to accommodate security definitions in the generated 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");
    })

这篇关于带Swashbuckle的标头中的API密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆