nestjs-redoc
nestjs-redoc copied to clipboard
swagger.json not secured
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
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,
},
);
// ...