赞
踩
nestjs经常需要设置一些鉴权(登录后)才能访问的接口,但是生成的swagger文档可以发起接口请求,文档发起的请求默认是不携带登录token的,所以需要移除swagger文档发起请求的守卫拦截。
nestjs守卫拦截设置见另一篇博客 nestjs守卫/全局守卫校验jwt-CSDN博客
global.guard.ts
- import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
-
- @Injectable()
- export class GlobalGuard implements NestInterceptor {
- intercept(context: ExecutionContext, next): Observable<any> {
- const request = context.switchToHttp().getRequest();
- // 判断是否是swagger文档访问,如果请求头referer包含/api-docs,则认为是swagger文档访问
- // 文档前缀在main.ts设置,本项目文档前缀设置的api-docs
- const apiDocAccess = request.headers['referer'].indexOf('/api-docs') > -1;
- if (!apiDocAccess) {
- // 非文档访问、需要鉴权才能访问的接口,执行鉴权逻辑
- // ...
- }
- // 其他场景直接放行
- return next.handle();
- }
- }

接口添加 jwt 鉴权后,接口文档调用接口请求头没有添加 authorization,请求会返回403。为此,需要给文档需要鉴权的接口请求头也添加 authorization
- const config = new DocumentBuilder()
- .setTitle('接口文档')
- .setDescription('接口文档描述')
- .setVersion('1.0')
- .addBearerAuth() // 注意此处:文档添加BearerAuth
- .build();
- const document = SwaggerModule.createDocument(app, config);
- SwaggerModule.setup('api-docs', app, document); // 文档前缀设为 api-docs
- import { ApiBearerAuth } from '@nestjs/swagger';
-
- @Controller('api')
- @ApiBearerAuth() // 在此处添加,表示/api/的接口请求头全都需要添加authorization
- export class ApiController {
-
- @Get('getUserInfo')
- @UseGuards(AuthGuard)
- @ApiBearerAuth() // 在此处添加,表示当前接口请求头需要添加authorization
- getUserInfo(): any {
- return this.apiService.getUserInfo();
- }
- }
先调用登录接口获取到 jwt_token
注意:可以设置默认请求参数,参数用一个swagger测试账号,就不用每次调用再改参数了。设置方法如下:
- class LoginDto {
- @ApiProperty({description: '用户名', default: 'swagger-test'})
- name: string
- @ApiProperty({description: '密码', default: '123456'})
- password: string
- }
点击文档顶部Authorize按钮
输入获取到的 jwt_token,并点击Authorize,然后关闭弹窗
再调用需要鉴权的接口,就可以鉴权通过了
注意:请求头的 Authorization 参数会在最前面添加 Bearer 字符,可以在守卫中将此字符移除
this.jwtService.verify(token.replace('Bearer ', ''))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。