@nestjs/swagger 没有设置授权 headers

@nestjs/swagger does not set authorization headers

无法在使用 @nestjs/swagger@5.0.9 的路由中授权,因为我没有以正确的方式使用 t know how to configure the Document`,而且我找不到 可行的 在授权官方文档/Whosebug/github.

中回答

我无意中发现了 JWT 授权问题。我正在使用 "@nestjs/swagger": "^5.0.9" 并且在我从 public 路线获得我的 access-token 之后,我将它插入到 swagger ui 字段 'Authorize' 中配置了 .addBearerAuth() 方法,在这个版本(5.0.9)中有这个签名

addBearerAuth(options?: SecuritySchemeObject, name?: string)

相对于it lower version.

我已经在 Postman 中测试了我的 API,我很容易获得授权,我还创建了一个在路由调用之前打印 headers 的交叉部分,但不幸的是它只在我调用 public 路由时打印它们:/

我只知道 Postman 正在设置一个 Bearer 令牌,它会抛出路由,而 swagger 没有发生类似的事情。

我已经尝试了很多这种配置的组合,但我还没有找到一个解决方案,结果我在我的路由方法中获得了授权,因为 swagger 我无法访问它,因为swagger auth 没有设置授权 header 以防配置错误或我做错了事。我也想不通。

一个addBearerAuth的配置放低了:

// swagger config
...
const config = new DocumentBuilder()
    .setTitle('SWAGGER API')
    .setVersion('1.0.0')
    .addBearerAuth(
      { 
        // I was also testing it without prefix 'Bearer ' before the JWT
        description: `[just text field] Please enter token in following format: Bearer <JWT>`,
        name: 'Authorization',
        bearerFormat: 'Bearer', // I`ve tested not to use this field, but the result was the same
        scheme: 'Bearer',
        type: 'http', // I`ve attempted type: 'apiKey' too
        in: 'Header'
      },
      'access-token',
    )
    .build();
...

我的控制器中的路线示例。与 @ApiBearerAuth() 装饰器相匹配,装饰器大摇大摆地说未经授权无法访问该方法。

@Get('/some-route')
@ApiBearerAuth()
@UseGuards(JwtAuthenticationGuard)
getData(
  @ReqUser() user: User,
): void {
  this.logger.warn({user});
}

如果我理解你的问题,你需要在你的控制器中指定你正在使用的不记名令牌。你的情况:

// swagger config
...
const config = new DocumentBuilder()
    .setTitle('SWAGGER API')
    .setVersion('1.0.0')
    .addBearerAuth(
      { 
        // I was also testing it without prefix 'Bearer ' before the JWT
        description: `[just text field] Please enter token in following format: Bearer <JWT>`,
        name: 'Authorization',
        bearerFormat: 'Bearer', // I`ve tested not to use this field, but the result was the same
        scheme: 'Bearer',
        type: 'http', // I`ve attempted type: 'apiKey' too
        in: 'Header'
      },
      'access-token', // This name here is important for matching up with @ApiBearerAuth() in your controller!
    )
    .build();
...

并在您的控制器中:

@Get('/some-route')
@ApiBearerAuth('access-token') //edit here
@UseGuards(JwtAuthenticationGuard)
getData(
  @ReqUser() user: User,
): void {
  this.logger.warn({user});
}