我在AngularJs SPA中使用swagger-js / swagger-client(https://github.com/swagger-api/swagger-js)来使用TryItOut Executor向nodeJS服务器发送REST请求。
我正在使用PassportJS进行身份验证。当我使用Angular的$ http服务并将withCredentials属性设置为true时:
$http({
method: 'GET',
withCredentials: true,
url: 'http://someUrl/someRestPath/' })
,一切正常 - 浏览器cookie已正确设置,并且每个进一步的请求都已成功通过身份验证。
切换到swagger-js执行程序,由于未设置cookie,因此无法正确进行身份验证。我尝试过以下方法:
var swaggerClient = new SwaggerClient(specUrl)
.then(function (swaggerClient) {
swaggerClient.http.withCredentials = true; // this activates CORS, if necessary
正如文档中所建议的那样但这没有效果。虽然我在使用护照进行身份验证时会收到凭据,但由于未设置Cookie,因此未经授权进一步请求。
Left: cookies not being sent; Right: cookies being set
如何使用swagger-js启用此行为?
答案 0 :(得分:1)
我能够找到解决方案。 Swagger-js客户端的execute方法允许我们定义自己的http方法。我简单地使用了有角度的$ http服务,其中.Credentials在.config中全局设置为true
import Swagger from 'swagger-client';
<。>在.config中:
angular.module('app', []).config(['$httpProvider',function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}
然后当你创建你的招摇客户端时:
Swagger({ url: 'some swagger specification (yaml/json)' }).then(client => {
client.execute({ http: $http, operationId: operationId, parameters: parameters});