为什么“接受的答案”有效...但对我来说还不够
这在规范中有效。至少 swagger-tools(版本 0.10.1)将其验证为有效。
但是如果您使用其他工具,例如swagger-codegen(2.1.6 版),您会发现一些困难,即使生成的客户端包含身份验证定义,如下所示:
this.authentications = {
'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};
在调用方法(端点)之前,无法将令牌传递到标头中。查看此函数签名:
this.rootGet = function(callback) { ... }
这意味着,我只传递没有令牌的回调(在其他情况下是查询参数等),这会导致对服务器的请求构建不正确。
我的选择
不幸的是,它并不“漂亮”,但在我在 Swagger 上获得 JWT 令牌支持之前它一直有效。
注意:这是在讨论
因此,它像标准标头一样处理身份验证。在path 对象上附加一个标头参数:
swagger: '2.0'
info:
version: 1.0.0
title: Based on "Basic Auth Example"
description: >
An example for how to use Auth with Swagger.
host: localhost
schemes:
- http
- https
paths:
/:
get:
parameters:
-
name: authorization
in: header
type: string
required: true
responses:
'200':
description: 'Will send `Authenticated`'
'403':
description: 'You do not have necessary permissions for the resource'
这将在方法签名上生成一个带有新参数的客户端:
this.rootGet = function(authorization, callback) {
// ...
var headerParams = {
'authorization': authorization
};
// ...
}
要正确使用此方法,只需传递“完整字符串”
// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);
并且有效。