expressswaggernestjsswagger-uinestjs-swagger

Swagger UI & express-basic-auth returns 401 in all my routes instead of provided on app.use params


I have this swagger implementation, and i just give it a simple auth validation with express-basic-auth before anyone can access the UI, but with this implementation, every route returns 401

But this broke all my routes, but now is being aplied to all my routes instead of given routes in the array

Anyone have any idea why NestJs is not respecting the express middleware -> app.use( [ ROUTE-1, ROUTE- 2 ], middleware ) ?

This make all my request return 401 in my app :(

I follow this answer and it won't work :/

Anyone knows why nestjs do this?

Thanks for reading

main.ts :

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import * as basicAuth from 'express-basic-auth';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableCors();

  app.useGlobalPipes(
    new ValidationPipe({
      // Ignorar datos que no esten en los DTO
      whitelist: true,
      // Lanzar error si existen datos prohibidos
      forbidNonWhitelisted: true,
      // Desabilitar mensajes de error (producción)
      disableErrorMessages: process.env.NODE_ENV == 'production' ? true : false,
    }),
  );
  // -> ERROR START HERE
  // THIS NOT WORK
  app.use(
    ['/api', '/api-json'],
    basicAuth({
      challenge: true,
      users: {
        site: process.env.DOCS_PASSWORD || '00000',
      },
    }),
  );
  // -> ERROR ENDS HERE
  const config = new DocumentBuilder()
    .setTitle('Demo sites')
    .setDescription('Demo API sites')
    .setVersion('v1')
    .addTag('API sites')
    .addBearerAuth(
      {
        description: 'JWT Authorization with Auth0',
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
      },
      'Auth0 JWT',
    )
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document, {
    explorer: true,
    swaggerOptions: {
      filter: true,
      showRequestDuration: true,
    },
  });

  await app.listen(process.env.PORT || 8000);
}
bootstrap();

Solution

  • I solved changing the swagger route to /docs , be careful setting the SwaggerModule.setup(-->'api'<--...)

    and app.use(['api'...]

    I dindnt know that was a wildcard, it was clashing with my REST routes -> '/api/v1/resource'