如何配置安全性以允许仅通过nodejs中的身份验证访问swagger url

How to configure security to allow swagger url to be accessed only with authentication in nodejs

我在 node 中集成了 swagger,可以在 http://localhost:3002/api-docs 上访问它。但是招摇 ui 是公开的。我想添加 authentication/security 以访问此路由。当用户点击 http://localhost:3002/api-docs 时,它应该显示 popup/prompt 以输入 username/password。如果用户名和密码正确,那么只有用户才能看到 swagger UI.

可能如下图所示

我正在使用 swagger-ui-express,这是我正在使用的代码

import swaggerUi from 'swagger-ui-express';
import * as swaggerDocument from './swagger.json' 

....
....

app.use("/api-docs",swaggerUi.serve,swaggerUi.setup(swaggerDocument));


我在互联网上搜索但没有找到任何解决方案。我找到了一个 但它在 spring.

提前致谢!!

您可以插入一个 basic-auth 中间件(例如 https://github.com/LionC/express-basic-auth)来保护 swagger-ui 路由。如果您使用 express-basic-auth,请确保设置 challenge option 以强制浏览器打开提示:

const basicAuth = require('express-basic-auth');

app.use("/api-docs",basicAuth({
    users: {'yourUser': 'yourPassword'},
    challenge: true,
}), swaggerUi.serve, swaggerUi.setup(swaggerDocument));