【问题标题】:Is cookie authentication supported in nestjs swagger?nestjs swagger 是否支持 cookie 身份验证?
【发布时间】:2021-01-29 08:34:32
【问题描述】:

我想在我的 swagger 文档中包含 cookie 授权,但是我似乎没有取得任何进展。

根据https://docs.nestjs.com/openapi/security,nestjs-swagger 似乎支持 cookie 身份验证。

但是,根据 Swagger UI 和编辑器的 https://swagger.io/docs/specification/authentication/cookie-authentication/,“试用”不支持 cookie 身份验证

我不确定我是否错误地实现了 cookie 身份验证,或者它是否不受支持。

下面是我正在尝试的实现。

在 DocumentBuilder() 中:

.addCookieAuth('authCookie')

在控制器中:

@ApiCookieAuth()

我尝试将我的 cookie 名称“authCookie”添加到 @ApiCookieAuth() 标记中。 我也尝试过使用.addCookieAuth('authCookie', {type: 'apiKey',in: 'cookie'})

我尝试任何方式都会收到未找到 JWT 令牌的错误。我知道当我使用邮递员时这确实有效,所以我很困惑为什么会遇到这个问题。

【问题讨论】:

    标签: node.js express swagger nestjs openapi


    【解决方案1】:

    基本上,你可以使用

      SwaggerModule.setup('swagger', app, document, {
        swaggerOptions: {
          requestInterceptor: (req) => {
            req.credentials = 'include';
            return req;
          },
        },
      });
    

    请注意,手动设置 cookie 值不会对 Fetch 请求产生任何影响。

    swagger-client有关,与NestJs无关

    【讨论】:

      【解决方案2】:

      我的一个解决办法是在DocumentBuilder 中使用这样的options

      .addCookieAuth('authCookie', {
        type: 'http',
        in: 'Header',
        scheme: 'Bearer'
      })
      

      以及控制器中的这样的装饰器:

      @ApiCookieAuth()
      

      如果您需要指定 cookie 名称,有一个 securityName 参数将指定 cookie 应用内的名称

      .addCookieAuth(cookieName?: string, options?: SecuritySchemeObject, securityName?: string)
      

      在您指定 securityName 之后,您还需要将其提供给控制器装饰器:

      DocumentBuilder

      .addCookieAuth('auth-cookie', {
        type: 'http',
        in: 'Header',
        scheme: 'Bearer'
      },
      'in-app-cookie-name')
      

      在控制器中:

      @ApiCookieAuth('in-app-cookie-name')
      

      此解决方案在手动将 JWT 插入到 swagger auth 输入后才起作用。如果我做对了 - SwaggerUI 不支持自动插入 cookie 字段。

      link with this issue on GitHub

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-12
        • 2016-05-01
        • 1970-01-01
        • 2020-01-08
        • 1970-01-01
        • 1970-01-01
        • 2015-07-04
        • 2014-01-31
        相关资源
        最近更新 更多