【发布时间】:2021-10-18 20:40:09
【问题描述】:
无法在使用@nestjs/swagger@5.0.9 的路由中进行授权,因为我没有以正确的方式使用t know how to configure the Document`,并且在授权官方文档/stackoverflow/github 中找不到可行 答案.
我在 Swagger 中偶然发现了 JWT 授权的问题。我正在使用"@nestjs/swagger": "^5.0.9",在从公共路由获取访问令牌后,我将其插入到配置有.addBearerAuth() 方法的swagger ui 字段“授权”中,在这个版本中(5.0 .9) 有这个签名
addBearerAuth(options?: SecuritySchemeObject, name?: string)
相对于it lower version。
我已经在 Postman 中测试了我的 API,并且很容易获得授权,我还创建了一个在路由调用之前打印标题的交叉器,但不幸的是它只在我调用公共时打印它们路线:/
我只知道 Postman 正在设置一个 Bearer 令牌并且它会抛出路由,而 swagger 并没有发生类似的事情。
我已经尝试了很多这种配置的组合,但我还没有找到一个解决方案,结果我在我的路由方法中获得了授权,从大摇大摆我无法达到它,因为 swagger auth 没有设置授权标头,以防配置错误或我做错了什么。而且我想不通。
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});
}
【问题讨论】:
标签: javascript swagger nestjs nestjs-swagger nestjs-jwt