在 Linux 环境下使用 Swagger(OpenAPI) 做接口文档时,“鉴权”通常指两件事之一:
下面分别说明,偏实战。
如果是 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;
}
适合任何 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;
}
用 swagger-api/swagger-ui 镜像:
docker run -d \
-e SWAGGER_JSON=/foo/swagger.json \
-p 8080:8080 \
swaggerapi/swagger-ui
再加 Nginx 反向代理 + Basic Auth 即可。
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
security:
- ApiKeyAuth: []
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
security:
- BearerAuth: []
Swagger UI 中点击 Authorize,填:
Bearer eyJhbGciOi...
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
| 场景 | 推荐方案 |
|---|---|
| 内部接口 | Nginx IP 白名单 |
| 对外文档 | Nginx Basic Auth |
| 微服务 | Spring Security |
| 云环境 | API 网关鉴权 |
如果你能告诉我:
我可以直接给你一份可复制的配置。