首页 文章

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

提问于
浏览
15

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

对于Authenticate REST调用,我在标头中使用API密钥 .

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

我想让用户使用自己的API密钥生成客户端,因此他不再需要在代码中手动设置API密钥 .

在我的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对象,但没有关于它的文档(或者我找不到它) .

It would be sufficient to be able to be able to have the generated client lib add an arbitrary HTTP header to all requests.

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

X-ApiKey:{whatever the key is}

有人有想法吗?

非常感谢!

1 回答

  • 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" } }
                }
    

相关问题