Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swagger.json not secured #71

Open
NewEXE opened this issue Jun 29, 2023 · 1 comment
Open

swagger.json not secured #71

NewEXE opened this issue Jun 29, 2023 · 1 comment

Comments

@NewEXE
Copy link

NewEXE commented Jun 29, 2023

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
#19 (comment)

@NewEXE
Copy link
Author

NewEXE commented Jul 5, 2023

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,
    },
  );

// ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant