温馨提示×

linux swagger如何鉴权

小樊
47
2026-09-03 13:14:05
栏目: 智能运维

在 Linux 环境下使用 Swagger(OpenAPI) 做接口文档时,“鉴权”通常指两件事之一:

  1. Swagger UI 本身的访问鉴权(防止别人直接看你的接口文档)
  2. Swagger 文档中接口的鉴权方式说明与测试(如 JWT、API Key、OAuth2)

下面分别说明,偏实战。


一、Swagger UI 本身的鉴权(保护文档)

1. Spring Boot(最常见)

如果是 Java 项目:

spring:
  swagger:
    enable: true

用 Spring Security 保护:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
      .antMatchers("/swagger-ui/**", "/v3/api-docs/**")
      .authenticated()
      .and()
      .httpBasic();
}

或仅内网访问(Linux 层):

location /swagger-ui/ {
    allow 192.168.1.0/24;
    deny all;
}

2. Nginx + Basic Auth(Linux 通用)

适合任何 Swagger UI(Node、Docker、静态文件)

sudo apt install apache2-utils
htpasswd -c /etc/nginx/swagger.passwd admin

Nginx 配置:

location /swagger-ui/ {
    auth_basic "Swagger";
    auth_basic_user_file /etc/nginx/swagger.passwd;
}

3. Docker 部署 Swagger

swagger-api/swagger-ui 镜像:

docker run -d \
  -e SWAGGER_JSON=/foo/swagger.json \
  -p 8080:8080 \
  swaggerapi/swagger-ui

再加 Nginx 反向代理 + Basic Auth 即可。


二、Swagger 中接口的鉴权说明(给前端看 & 测试)

1. API Key 鉴权

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-KEY

security:
  - ApiKeyAuth: []

2. JWT(Bearer Token)

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - BearerAuth: []

Swagger UI 中点击 Authorize,填:

Bearer eyJhbGciOi...

3. OAuth2(企业常用)

components:
  securitySchemes:
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/oauth2/authorize
          tokenUrl: https://auth.example.com/oauth2/token
          scopes:
            read: read data

三、Linux 下常见组合推荐

场景 推荐方案
内部接口 Nginx IP 白名单
对外文档 Nginx Basic Auth
微服务 Spring Security
云环境 API 网关鉴权

如果你能告诉我:

  • 用的是 Swagger 2 还是 OpenAPI 3
  • 什么语言(Java / Go / Node)
  • 是否用 Docker / Nginx

我可以直接给你一份可复制的配置

0