如何在Node.js中配置认证,仅允许授权用户访问Swagger文档路由
Got it, let's fix that! To add a username/password prompt for your Swagger UI (using HTTP Basic Authentication, which triggers the browser's native login dialog), you have two solid options—either roll your own simple middleware or use a trusted package. Here's how to do both:
Option 1: Custom Basic Auth Middleware (No extra packages)
If you don't want to add another dependency, you can create a minimal middleware to handle the authentication check:
import swaggerUi from 'swagger-ui-express'; import * as swaggerDocument from './swagger.json'; // Define your valid credentials (use environment variables in production!) const VALID_USER = 'your-secure-username'; const VALID_PASS = 'your-strong-password'; // Custom Basic Auth middleware const swaggerAuthMiddleware = (req, res, next) => { const authHeader = req.headers.authorization; // If no auth header exists, prompt the user to log in if (!authHeader || !authHeader.startsWith('Basic ')) { res.setHeader('WWW-Authenticate', 'Basic realm="Swagger UI"'); return res.status(401).send('Authentication required to access Swagger UI'); } // Decode the base64-encoded credentials const base64Credentials = authHeader.split(' ')[1]; const [username, password] = Buffer.from(base64Credentials, 'base64').toString('utf8').split(':'); // Validate credentials if (username === VALID_USER && password === VALID_PASS) { return next(); // Proceed to Swagger UI } // Invalid credentials: prompt again res.setHeader('WWW-Authenticate', 'Basic realm="Swagger UI"'); return res.status(401).send('Invalid username or password'); }; // Add the auth middleware BEFORE the Swagger UI handlers app.use("/api-docs", swaggerAuthMiddleware, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
Option 2: Use
express-basic-auth Package (Simpler) For a more robust, maintainable solution, use the express-basic-auth package—it handles edge cases and configuration for you:
- First install the package:
npm install express-basic-auth
- Update your code to include the middleware:
import swaggerUi from 'swagger-ui-express'; import * as swaggerDocument from './swagger.json'; import basicAuth from 'express-basic-auth'; // Configure Basic Auth (use environment variables in production!) const swaggerAuth = basicAuth({ users: { 'your-secure-username': 'your-strong-password' }, challenge: true, // This triggers the browser's login dialog realm: 'Swagger UI' // Text shown in the login prompt }); // Apply the auth middleware to the Swagger route app.use("/api-docs", swaggerAuth, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
Important Notes
- Never hardcode credentials! In production, use environment variables (e.g.,
process.env.SWAGGER_USERandprocess.env.SWAGGER_PASSWORD) instead of writing them directly in your code. - Use HTTPS in production: Basic Authentication sends credentials as base64-encoded text (not encrypted), so always serve your app over HTTPS to prevent credential theft.
- Realm text: The
realmvalue is what shows up in the browser's login dialog (e.g., "Please enter your credentials for Swagger UI").
内容的提问来源于stack exchange,提问作者Shivam Kubde
相关产品推荐
相关产品推荐

