wal*_*ld3 12 javascript swagger nestjs nestjs-swagger nestjs-jwt
无法在路线中授权,@nestjs/swagger@5.0.9因为我以t know how to configure the 正确的方式使用 Document`,并且在授权官方文档/stackoverflow/github 中找不到可行的答案。
我偶然发现了 JWT 授权的问题。我正在使用"@nestjs/swagger": "^5.0.9",在从公共路由获取访问令牌后,我将其插入到使用.addBearerAuth()方法配置的 swagger ui 字段“Authorize”中,在此版本(5.0.9)中具有此签名
addBearerAuth(options?: SecuritySchemeObject, name?: string)
Run Code Online (Sandbox Code Playgroud)
与较低版本相反。
我已经在 Postman 中测试了我的 API,并且很容易获得授权,我还创建了一个交集,它在路由调用之前打印标头,但不幸的是它只在我调用公共路由时打印它们:/
我只知道邮递员正在设置一个不记名令牌,并且它会抛出路线,并且 swagger 没有发生类似的情况。
我已经尝试了很多这种配置的组合,但我还没有找到一个解决方案,结果我在我的路由方法中获得了授权,从 swagger 我无法访问它,因为 swagger 身份验证不是设置授权标头,以防配置错误或我做了完全错误的事情。我无法弄清楚。
a的配置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();
...
Run Code Online (Sandbox Code Playgroud)
我的控制器中的路线示例。与一个装饰器相匹配,@ApiBearerAuth()该装饰器正在与一个大摇大摆的人交谈,未经授权就无法访问该方法。
@Get('/some-route')
@ApiBearerAuth()
@UseGuards(JwtAuthenticationGuard)
getData(
@ReqUser() user: User,
): void {
this.logger.warn({user});
}
Run Code Online (Sandbox Code Playgroud)
And*_*nai 16
如果我理解您的问题,您需要在控制器中指定您正在使用哪个不记名令牌。在你的情况下:
// 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();
...
Run Code Online (Sandbox Code Playgroud)
在你的控制器中:
@Get('/some-route')
@ApiBearerAuth('access-token') //edit here
@UseGuards(JwtAuthenticationGuard)
getData(
@ReqUser() user: User,
): void {
this.logger.warn({user});
}
Run Code Online (Sandbox Code Playgroud)