使用Swagger生成的客户端时标头中的硬编码Api键值

时间:2016-05-25 12:54:01

标签: swagger api-key swashbuckle swagger-codegen

我在C#中编写了许多API,并使用Swashbuckle创建了一个“Swagger”文档网站。

对于Authenticate REST调用,我在标题中使用API​​密钥。

我创建了一个页面,允许下载任何编程语言的特定客户端,如下所示:https://generator.swagger.io

我想让用户使用自己的API Key生成客户端,这样他就不需要再在代码中手动设置API Key。

在我的Swagger JSON中,我有这个安全定义:

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

在Swagger Client Generator的页面中,我发现这个模型允许设置客户端选项,但我无法找到客户端代码中API密钥是如何(以及是否)进行硬编码(或任何其他类型的授权)。

GeneratorInput {
    spec (object, optional),
    options (object, optional),
    swaggerUrl (string, optional),
    authorizationValue (AuthorizationValue, optional),
    securityDefinition (SecuritySchemeDefinition, optional)
}
AuthorizationValue {
    value (string, optional),
    type (string, optional),
    keyName (string, optional)
}
SecuritySchemeDefinition {
    description (string, optional),
    type (string, optional)
}

我想我必须设置AuthorizationValue对象,但没有关于它的文档(或者我找不到它)。

能够让生成的客户端lib为所有请求添加任意HTTP标头就足够了。

在这种情况下,我们可以添加:

X-ApiKey:{whatever the key is}

有人有想法吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

似乎可以简单地将它作为参数添加到每个调用的默认值 - 所以JSON会有这样的东西:

"post": {
                "tags": [ "user" ],
                "summary": "Creates list of users with given input array",
                "description": "",
                "operationId": "createUsersWithListInput",
                "produces": [ "application/xml", "application/json" ],
                "parameters": [
                    {
                        "in": "body",
                        "name": "body",
                        "description": "List of user object",
                        "required": true,
                        "schema": {
                            "type": "array",
                            "items": { "$ref": "#/definitions/User" }
                        }
                    },
                    {
                        "in": "header",
                        "name": "X-ApiKey",
                        "required": false,
                        "type": "string",
                        "format": "string",
                        "default": "abcdef12345"
                    }
                ],
                "responses": { "default": { "description": "successful operation" } }
            }