【问题标题】:Enabling browser cookies with Swagger-js使用 Swagger-js 启用浏览器 cookie
【发布时间】:2018-02-21 10:21:50
【问题描述】:

我在 AngularJs SPA 中使用 swagger-js/swagger-client (https://github.com/swagger-api/swagger-js) 使用 TryItOut 执行器将 REST 请求发送到 nodeJS 服务器。

我正在使用 PassportJS 进行身份验证。当我使用 Angular 的 $http 服务并将 withCredentials 属性设置为 true 时:

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

,一切正常 - 浏览器 cookie 已正确设置,并且每个进一步的请求都已成功验证。

切换到 swagger-js Executor,由于未设置 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 启用此行为?

【问题讨论】:

    标签: angularjs http cookies swagger


    【解决方案1】:

    我找到了解决方案。 Swagger-js 客户端的 execute 方法允许我们定义自己的 http 方法。我只是在 .config 中使用 angular 的 $http 服务,并将 withCredentials 全局设置为 true

    import Swagger from 'swagger-client';
    

    在.config中:

    angular.module('app', []).config(['$httpProvider',function ($httpProvider) {
        $httpProvider.defaults.withCredentials = true;
    }
    

    然后当你创建你的 swagger 客户端时:

    Swagger({ url: 'some swagger specification (yaml/json)' }).then(client => {
        client.execute({ http: $http, operationId: operationId, parameters: parameters});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多