You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node/Express.js项目中为swagger-ui配置登录验证表单

实现方案(基于Express路由拦截+自定义登录校验)

第一步:配置登录态基础依赖

以常用的session存储登录态为例,先安装依赖并在项目入口完成基础配置:

npm install express-session

在项目入口app.js中添加session配置:

const session = require('express-session');
app.use(session({
  secret: '自定义加密密钥',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 24 * 60 * 60 * 1000 } // 登录态有效期可自行调整
}))

第二步:编写登录校验逻辑

添加登录状态校验中间件、登录表单提交处理接口:

// swagger访问权限校验中间件
const checkSwaggerAuth = (req, res, next) => {
  // 已登录直接放行到swagger页面
  if(req.session.swaggerLogged) return next()
  // 未登录返回登录表单
  res.send(`
    <div style="width: 300px; margin: 100px auto;">
      <h3>API文档登录</h3>
      <form method="POST" action="/api-docs/login">
        <div style="margin: 10px 0;">
          <label>用户名:</label>
          <input type="text" name="username" required style="width: 100%; padding: 6px; margin-top: 4px;">
        </div>
        <div style="margin: 10px 0;">
          <label>密码:</label>
          <input type="password" name="password" required style="width: 100%; padding: 6px; margin-top: 4px;">
        </div>
        <button type="submit" style="width: 100%; padding: 8px; background: #409eff; color: #fff; border: none; border-radius: 4px; cursor: pointer;">登录</button>
      </form>
    </div>
  `)
}

// 登录请求处理接口
app.post('/api-docs/login', express.urlencoded({ extended: true }), (req, res) => {
  const { username, password } = req.body
  // 此处替换为你自己的账号密码校验逻辑,比如读数据库对比
  if(username === '自定义账号' && password === '自定义密码') {
    req.session.swaggerLogged = true
    return res.redirect('/api-docs')
  }
  res.send('用户名或密码错误,<a href="/api-docs">返回重试</a>')
})

第三步:修改swagger配置,添加校验拦截

把校验中间件放到swagger路由处理之前即可,修改你的swagger配置文件代码:

const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('../swagger.json');

const options = {
    apis: ['../routes/index.js'],
    swaggerDefinition: swaggerDocument    
}
const specs = swaggerJsDoc(options);
module.exports = (app) => {
  // 校验中间件放在最前面,未登录用户无法进入swagger页面
  app.use('/api-docs', checkSwaggerAuth, swaggerUi.serve, swaggerUi.setup(specs, {
      explorer: true
  }));
}

可选扩展:swagger接口调用统一授权

如果除了页面访问权限,还需要在swagger内调用接口时自动携带授权信息,可以在swagger.json的paths同级添加安全配置:

{
    "openapi": "3.0.0",
    "info": {
        "title": "REST API",
        "version": "1.0.0",
        "description": "Desc. REST API"
    },
    "schema": [
        "http",
        "https"
    ],
    "servers": [
        {
            "url": "http://localhost:3000/"
        }
    ],
    "components": {
      "securitySchemes": {
        "BearerAuth": {
          "type": "http",
          "scheme": "bearer",
          "bearerFormat": "JWT"
        }
      }
    },
    "security": [
      {
        "BearerAuth": []
      }
    ],
    "paths": {
    //rest of the paths...
    }
}

配置完成后swagger页面右上角会出现Authorize按钮,用户可以自行填入token,后续调用接口时会自动携带在请求头中。

内容的提问来源于stack exchange,提问作者Mohamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 09:15:01