如何保护nestjs swagger端点

a0x5cqrl  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(84)

当swagger模块安装在main.ts文件上时,你如何在nestjs上保护swagger文档?

const options = new DocumentBuilder()
      .setTitle("API")
      .setDescription("NestJS api")
      .setVersion("1.0")
      .build();
    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup("swagger", app, document);

字符串
我期待使用像下面的 Swagger 文档端点后卫。

@UseGuards(RolesGuard)

ef1yzkbh

ef1yzkbh1#

我建议你使用Interceptors,如果你想留在NestJS设计
或者你可以在app中使用expressfastify认证中间件bootstrap方法,请参阅this ticket获取灵感(旧版NestJS)

2j4z5cfb

2j4z5cfb2#

我认为你在完成这个NestJs process后面临的只是swagger头问题。如果是的话,你只需要像这样将.addBearerAuth()添加到swagger配置选项中:

const config = new DocumentBuilder()
  .setTitle('REST API BY NEST')
  .setDescription('ITS A REST API')
  .setVersion('1.0')
  .addBearerAuth()
  //You can also add this to .addBearerAuth({type:'http', scheme: 'bearer',  bearerFormat: 'JWT', in:'header'})
  .build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

字符串
完成此操作后,您需要在@UseGuards(AuthGuard)之前添加@ApiBearerAuth() Swagger Decorator,如下所示:

@ApiBearerAuth()
@UseGuards(AuthGuard)
  @Get('profile')
  getProfile(@Request() req) {
    const user= this.userService.findAll();
    return user;
  }


或者你可以像这样添加到一个整体控制器:

@ApiBearerAuth()
@UseGuards(AuthGuard)
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }


现在一切正常运行API

相关问题