当前位置:   article > 正文

nestjs swagger文档调用需要鉴权的接口_nestjs @apibearerauth 无效

nestjs @apibearerauth 无效

目标

nestjs经常需要设置一些鉴权(登录后)才能访问的接口,但是生成的swagger文档可以发起接口请求,文档发起的请求默认是不携带登录token的,所以需要移除swagger文档发起请求的守卫拦截。

nestjs守卫拦截设置见另一篇博客 nestjs守卫/全局守卫校验jwt-CSDN博客

方案一

关闭swagger文档请求守卫拦截

global.guard.ts

  1. import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
  2. @Injectable()
  3. export class GlobalGuard implements NestInterceptor {
  4. intercept(context: ExecutionContext, next): Observable<any> {
  5. const request = context.switchToHttp().getRequest();
  6. // 判断是否是swagger文档访问,如果请求头referer包含/api-docs,则认为是swagger文档访问
  7. // 文档前缀在main.ts设置,本项目文档前缀设置的api-docs
  8. const apiDocAccess = request.headers['referer'].indexOf('/api-docs') > -1;
  9. if (!apiDocAccess) {
  10. // 非文档访问、需要鉴权才能访问的接口,执行鉴权逻辑
  11. // ...
  12. }
  13. // 其他场景直接放行
  14. return next.handle();
  15. }
  16. }

方案二

swagger文档添加鉴权请求头信息

接口添加 jwt 鉴权后,接口文档调用接口请求头没有添加 authorization,请求会返回403。为此,需要给文档需要鉴权的接口请求头也添加 authorization

main.ts 配置 BearerAuth 校验
  1. const config = new DocumentBuilder()
  2. .setTitle('接口文档')
  3. .setDescription('接口文档描述')
  4. .setVersion('1.0')
  5. .addBearerAuth() // 注意此处:文档添加BearerAuth
  6. .build();
  7. const document = SwaggerModule.createDocument(app, config);
  8. SwaggerModule.setup('api-docs', app, document); // 文档前缀设为 api-docs
在需要鉴权的接口添加 @ApiBearerAuth() 装饰器
  1. import { ApiBearerAuth } from '@nestjs/swagger';
  2. @Controller('api')
  3. @ApiBearerAuth() // 在此处添加,表示/api/的接口请求头全都需要添加authorization
  4. export class ApiController {
  5. @Get('getUserInfo')
  6. @UseGuards(AuthGuard)
  7. @ApiBearerAuth() // 在此处添加,表示当前接口请求头需要添加authorization
  8. getUserInfo(): any {
  9. return this.apiService.getUserInfo();
  10. }
  11. }
使用

先调用登录接口获取到 jwt_token

注意:可以设置默认请求参数,参数用一个swagger测试账号,就不用每次调用再改参数了。设置方法如下:

  1. class LoginDto {
  2. @ApiProperty({description: '用户名', default: 'swagger-test'})
  3. name: string
  4. @ApiProperty({description: '密码', default: '123456'})
  5. password: string
  6. }

点击文档顶部Authorize按钮

输入获取到的 jwt_token,并点击Authorize,然后关闭弹窗

再调用需要鉴权的接口,就可以鉴权通过了

注意:请求头的 Authorization 参数会在最前面添加 Bearer 字符,可以在守卫中将此字符移除

this.jwtService.verify(token.replace('Bearer ', ''))
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/478665
推荐阅读
相关标签
  

闽ICP备14008679号