'Ask for credentials before showing my swagger

I'm trying to add security to my API swagger endpont. I have created my API using node.js and express and swagger-ui-express module. The problem is that anyone is able to access to my swagger endpoint. So, to solve this, I thought about adding a basic auth before showing swagger content.

enter image description here

Example of implementing basic auth on endpoint:

app.get('/users', (req, res) => {
    let user = auth(req)
    
    if (user === undefined || user['name'] !== 'admin' || user['pass'] !== 'adminpass') {
        res.statusCode = 401
        res.setHeader('WWW-Authenticate', 'Basic realm="Node"')
        res.end('Unauthorized')
    } else {
        res.status(200).send('Return all users');
    }
});

That same example I want to add in swagger's endpoint:

const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.yaml');

const swaggerOptions = {
    swaggerDefinition: {
        info: {
            version: "1.0.0",
            title: "Customer API",
            description: "Customer API Information",
            contact: {
                name: "Amazing Developer"
            },
            servers: ["http://localhost:3000"]
        }
    },
    // ['.routes/*.js']
    apis: ["index.js"]
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

Can anyone help me? I tried to do it but it doesn't work. I even don't know if it is possible.

SOLUTION:

app.use('/api-docs', function(req, res, next){
    let user = auth(req)
    if (user === undefined || user['name'] !== 'admin' || user['pass'] !== 'adminpass') {
        res.statusCode = 401
        res.setHeader('WWW-Authenticate', 'Basic realm="Node"')
        res.end('Unauthorized')
    } else {
        next();
    }
}, swaggerUi.serve, swaggerUi.setup(swaggerDocument));

Edit: for those asking, auth is a function that takes the base64 encoded credentaials from the request header, decodes them and returns an object. Like follows:

const auth = (req) => {
  const authorizationHeader = req.headers.authorization;
  const base64 = authorizationHeader.substr(6);
  const credentials = Buffer.from(base64, 'base64').toString();
  const [name, pass] = credentials.split(':');
  return { name, pass };
}


Solution 1:[1]

app.use('/api-docs', function(req, res, next){
    let user = auth(req)
    if (user === undefined || user['name'] !== 'admin' || user['pass'] !== 'adminpass') {
        res.statusCode = 401
        res.setHeader('WWW-Authenticate', 'Basic realm="Node"')
        res.end('Unauthorized')
    } else {
        next();
    }
}, swaggerUi.serve, swaggerUi.setup(swaggerDocument));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Santiago Moltó