ojoanalogo / nestjs-redoc

📘 ReDoc frontend for you NestJS swagger API documentation
MIT License
145 stars 56 forks source link

swagger.json not secured #71

Open NewEXE opened 1 year ago

NewEXE commented 1 year ago

When I'm protect my documentation with

    auth: {
      enabled: true,
      user: config.get('openapi.user'),
      password: config.get('openapi.password'),
    },

this works for main page, but doesn't protect access to swagger.json!!!

See related https://github.com/mxarc/nestjs-redoc/issues/19#issuecomment-743206567

NewEXE commented 1 year ago

As a workaround, you can use this solution:

// main.ts

import { NestExpressApplication, ExpressAdapter } from '@nestjs/platform-express';
import { Express, NextFunction, Request, Response } from 'express';
import createApplication from 'express';

/**
 * Fix: swagger.json is not secured
 * @param expressApp
 */
function setupSwaggerProtection(expressApp: Express) {
  const protection = (req: Request, res: Response, next: NextFunction) => {
    const authHeader = req.headers.authorization;

    if (authHeader) {
      const credentials = authHeader.split(' ')[1];
      const [username, password] = Buffer.from(credentials, 'base64')
        .toString()
        .split(':');

      if (
        // replace with your auth params
        username === 'USER' &&
        password === 'PASSWORD'
      ) {
        return next();
      }
    }

    res.setHeader('WWW-Authenticate', 'Basic realm="Restricted Area"');
    res.status(401).send('Authentication required');
  };

  // Replace openapi with your actual Redoc path
  expressApp.use('/openapi/swagger.json', protection);
}

async function bootstrap() {
  const expressApp = createApplication();
  setupSwaggerProtection(expressApp);

  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
    new ExpressAdapter(expressApp),
    {
      bufferLogs: true,
    },
  );

// ...