在 Linux 服务器上配置 Swagger 安全认证
总体思路
常见方案与落地示例
swagger: '2.0'
info:
title: Sample API
version: 1.0.0
securityDefinitions:
ApiKeyAuth:
type: apiKey
name: Authorization
in: header
paths:
/users:
get:
security:
- ApiKeyAuth: []
app.use((req,res,next)=>{
const key = req.headers['authorization'];
if (key === 'your-secret-api-key') next();
else res.status(401).send('Unauthorized');
});
securityDefinitions:
BasicAuth:
type: basic
paths:
/users:
get:
security:
- BasicAuth: []
http.authorizeRequests()
.antMatchers("/swagger-ui.html","/swagger-resources/**","/v2/api-docs").authenticated()
.and().httpBasic();
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]
反向代理与网关层保护
server {
listen 80;
server_name yourdomain.com;
location /api-docs/ {
auth_basic "Restricted Docs";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# 生成密码文件
sudo htpasswd -c /etc/nginx/.htpasswd username
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>
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any()).build()
.securitySchemes(Collections.singletonList(securityScheme()))
.securityContexts(Collections.singletonList(securityContext()));
}
private SecurityScheme securityScheme() {
return new SecurityScheme("basicAuth", SecurityScheme.Type.BASIC);
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.any()).build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope scope = new AuthorizationScope("global","accessEverything");
return Collections.singletonList(new SecurityReference("basicAuth", new AuthorizationScope[]{scope}));
}
生产环境注意事项