初始化 JS Swagger 客户端时传入 auth 凭据?
Pass in auth credentials when initializing JS Swagger client?
在 JS 中,我们通常在创建凭据时传入凭据,但 Swagger 的文档仅说明如何在创建客户端对象后执行此操作。
是的,只需创建一个授权对象,其密钥名称与 securityDefinitions
中的名称对齐,并将其传递给构造函数。假设安全定义为:
"securityDefinitions" : {
"sec_def_entry" : {
"type" : "apiKey",
"name" : "entry_name",
"in" : "header"
}
}
代码如下所示:
SwaggerClient = require('swagger-client'); //node
SwaggerClient = window.SwaggerClient; //browser
var auths = {
sec_def_entry : new SwaggerClient.ApiKeyAuthorization("entry_name", "special-key","header")
};
var client = new SwaggerClient({
"url": 'https://example.com/swagger.json',
authorizations: auths
})
但是请注意,这将导致 Swagger 在从服务器检索规范时传递凭据信息。如果您打开了基本授权,这可能会导致问题,因为 basic-auth 会触发选项预检(花费额外的往返时间和 requires setting the server to respond with a 200 respons to all options requests) and disallows wildcard origin in CORS.
在 JS 中,我们通常在创建凭据时传入凭据,但 Swagger 的文档仅说明如何在创建客户端对象后执行此操作。
是的,只需创建一个授权对象,其密钥名称与 securityDefinitions
中的名称对齐,并将其传递给构造函数。假设安全定义为:
"securityDefinitions" : {
"sec_def_entry" : {
"type" : "apiKey",
"name" : "entry_name",
"in" : "header"
}
}
代码如下所示:
SwaggerClient = require('swagger-client'); //node
SwaggerClient = window.SwaggerClient; //browser
var auths = {
sec_def_entry : new SwaggerClient.ApiKeyAuthorization("entry_name", "special-key","header")
};
var client = new SwaggerClient({
"url": 'https://example.com/swagger.json',
authorizations: auths
})
但是请注意,这将导致 Swagger 在从服务器检索规范时传递凭据信息。如果您打开了基本授权,这可能会导致问题,因为 basic-auth 会触发选项预检(花费额外的往返时间和 requires setting the server to respond with a 200 respons to all options requests) and disallows wildcard origin in CORS.