温馨提示×

Swagger在Linux环境下如何实现安全认证

小樊
39
2025-12-06 02:29:34
栏目: 智能运维

在 Linux 上保护 Swagger UI 与后端 API 的认证实践

总体思路

  • 将认证分为两层:
    1. 对文档入口(如 /api-docs/swagger-ui.html)做访问控制;
    2. OpenAPI/Swagger 规范中声明安全方案(如 BasicAPI KeyOAuth2),让 UI 展示“Authorize”并携带凭据。
  • 部署在 Linux 并无特殊差异,关键在于正确配置服务器中间件与规范文件的安全定义,并始终使用 HTTPS 保护凭据传输。

常见方案与最小示例

  • 下表给出三种常用方式与最简配置示例,便于快速落地:
方案 适用场景 OpenAPI 安全定义要点 服务端最小示例
Basic Auth 内部管理后台、测试环境 在规范中定义 type: basic 的安全方案 Express 使用 express-basic-auth 保护 /api-docs 路由
API Key 服务到服务调用、简单密钥校验 在规范中定义 type: apiKey,指定 in: header/queryname 中间件读取请求头(如 AuthorizationX-API-KEY)校验
OAuth 2.0 第三方授权、细粒度权限 在规范中定义 type: oauth2,配置 authorizationUrltokenUrlscopes 接入授权服务器;Swagger UI 通过 Authorize 按钮获取并刷新令牌
  • 示例要点(可直接复用):
    • OpenAPI 2.0 安全定义示例(Basic 与 API Key):
      swagger: '2.0'
      info:
        title: Sample API
        version: 1.0.0
      securityDefinitions:
        BasicAuth:
          type: basic
        ApiKeyAuth:
          type: apiKey
          name: Authorization
          in: header
      paths:
        /users:
          get:
            security:
              - BasicAuth: []
              - ApiKeyAuth: []
      
    • Express + Basic Auth 保护文档入口:
      const express = require('express');
      const basicAuth = require('express-basic-auth');
      const swaggerUi = require('swagger-ui-express');
      const YAML = require('yamljs');
      const swaggerDocument = YAML.load('./swagger.yaml');
      
      const app = express();
      app.use('/api-docs', basicAuth({
        users: { 'admin': 'secret' },
        challenge: true,
        unauthorizedResponse: { message: 'Unauthorized', status: 401 }
      }), swaggerUi.serve, swaggerUi.setup(swaggerDocument));
      
      app.listen(3000, () => console.log('Server on :3000'));
      
    • Express + API Key 校验示例(校验请求头中的密钥):
      app.use((req, res, next) => {
        const apiKey = req.headers['authorization']; // 或 X-API-KEY
        if (apiKey === 'your-secret-api-key') return next();
        res.status(401).send('Unauthorized');
      });
      
    • OAuth 2.0 在规范中声明(示例为授权码模式):
      securityDefinitions:
        OAuth2:
          type: oauth2
          flow: accessCode
          authorizationUrl: https://example.com/oauth/authorize
          tokenUrl: https://example.com/oauth/token
          scopes:
            read: Grants read access
            write: Grants write access
      paths:
        /users:
          get:
            security:
              - OAuth2: [read]
      
    上述示例展示了在规范层声明安全方案,以及在 Node.js/Express 中对文档入口实施 BasicAPI Key 校验的做法;OAuth 2.0 侧重规范声明与 UI 授权流程。

在 Spring Boot 项目中的落地

  • 引入依赖(示例为 Springfox Swagger 2Spring Security):
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
  • 配置 Spring Security(对文档入口启用 HTTP Basic 认证):
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
              .csrf().disable()
              .authorizeRequests()
                .antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**").authenticated()
                .anyRequest().authenticated()
              .and()
              .httpBasic();
        }
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
    
  • 说明:也可结合 OAuth2 或自定义 API Key 过滤器来保护文档与接口,思路与 Basic 认证一致,重点是对文档路径与应用接口统一鉴权。

部署与安全加固清单

  • 使用 反向代理/网关(如 Nginx)为文档与接口统一加一层 BasicAPI Key 保护,并强制 HTTPS;证书可用 Let’s Encrypt 自动签发。
  • 将文档与业务接口置于独立路径(如 /api-docs/swagger-ui/),仅在内网或受控网络开放;生产环境可禁用或限制 Swagger UI 对外暴露。
  • 对 API Key 使用足够长且随机的密钥,避免在代码中硬编码;支持密钥轮换与最小权限。
  • 启用 CORS 白名单、设置安全响应头(如 X-Frame-Options: DENYX-Content-Type-Options: nosniff)、开启访问日志与审计。
  • 定期升级 Swagger UI/Swagger Editor/相关依赖,修复已知漏洞。

0