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

huangapple go评论71阅读模式
英文:

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

问题

我有这个Swagger实现,并在任何人可以访问UI之前使用express-basic-auth进行了简单的身份验证,但是使用这个实现后,每个路由都返回401错误。

但是这破坏了我所有的路由,现在被应用到数组中的所有路由而不是给定的路由。

有人知道为什么NestJs不尊重express中间件 -> app.use([ROUTE-1, ROUTE-2], middleware)吗?

这使得我的应用程序中的所有请求都返回401错误 Swagger UI & express-basic-auth returns 401 in all my routes instead of provided on app.use params

我按照这个答案进行操作(https://stackoverflow.com/questions/54802832/is-it-possible-to-add-authentication-to-access-to-nestjs-swagger-explorer)但不起作用 :/

有人知道nestjs为什么会这样做吗?

感谢阅读

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({
      // Ignore data that is not in DTOs
      whitelist: true,
      // Throw an error if there are forbidden data
      forbidNonWhitelisted: true,
      // Disable error messages (production)
      disableErrorMessages: process.env.NODE_ENV == 'production' ? true : false,
    }),
  );

  // -> 错误从这里开始
  // 这不起作用
  app.use(
    ['/api', '/api-json'],
    basicAuth({
      challenge: true,
      users: {
        site: process.env.DOCS_PASSWORD || '00000',
      },
    }),
  );
  // -> 错误在这里结束

  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();
英文:

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 Swagger UI & express-basic-auth returns 401 in all my routes instead of provided on app.use params

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();

答案1

得分: 0

我已解决将Swagger路由更改为/docs,请注意设置SwaggerModule.setup(-->'api'<--...)

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

我不知道那是一个通配符,它与我的REST路由冲突 -> /api/v1/resource

英文:

I solved changing the swagger route to /docs , be careful setting the SwaggerModule.setup(--&gt;&#39;api&#39;&lt;--...)

and app.use([&#39;api&#39;...]

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

huangapple
  • 本文由 发表于 2023年6月8日 08:35:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427915.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定