2017-09-12 67 views
1

我在AngularJs SPA中使用Swagger-js/swagger-client(https://github.com/swagger-api/swagger-js)使用TryItOut執行程序將REST請求發送到nodeJS服務器。使用Swagger-js啓用瀏覽器cookie

我使用PassportJS進行身份驗證。當我使用角的$ HTTP服務與withCredentials屬性設置爲true:

$http({ 
     method: 'GET', 
     withCredentials: true, 
     url: 'http://someUrl/someRestPath/' }) 

,一切工作正常 - 瀏覽器的cookies設置是否正確,以及其後每請求被成功驗證。

切換到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

如何使用招搖-JS啓用此行爲?

回答

1

我能找到解決方案。 Swagger-js客戶端的執行方法允許我們定義自己的http方法。我只是用角的$ HTTP服務與的.config設置爲true全球在.config

import Swagger from 'swagger-client'; 

的withCredentials:

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});