在 Linux 上保护 Swagger UI 与后端 API 的认证实践
总体思路
常见方案与最小示例
| 方案 | 适用场景 | OpenAPI 安全定义要点 | 服务端最小示例 |
|---|---|---|---|
| Basic Auth | 内部管理后台、测试环境 | 在规范中定义 type: basic 的安全方案 | Express 使用 express-basic-auth 保护 /api-docs 路由 |
| API Key | 服务到服务调用、简单密钥校验 | 在规范中定义 type: apiKey,指定 in: header/query 与 name | 中间件读取请求头(如 Authorization 或 X-API-KEY)校验 |
| OAuth 2.0 | 第三方授权、细粒度权限 | 在规范中定义 type: oauth2,配置 authorizationUrl、tokenUrl 与 scopes | 接入授权服务器;Swagger UI 通过 Authorize 按钮获取并刷新令牌 |
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: []
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'));
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');
});
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]
在 Spring Boot 项目中的落地
<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>
@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();
}
}
部署与安全加固清单