Linux下Swagger提高API安全性的实用方案
一 网络与访问控制
二 认证与授权
三 文档内容与最小化暴露
四 运行时防护与运维
五 Nginx与Spring Boot快速配置示例
# 创建账号密码文件
sudo htpasswd -c /etc/nginx/.htpasswd admin
# server 或 location 配置
location /docs/ {
satisfy all;
allow 192.168.31.0/24;
allow 127.0.0.1;
deny all;
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;
}
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080/realms/myrealm
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt());
return http.build();
}
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(new Info().title("API Docs").version("v1"))
.components(new Components().addSecuritySchemes("keycloak_oauth",
new SecurityScheme()
.type(SecurityScheme.Type.OAUTH2)
.flows(new OAuthFlows()
.authorizationCode(new OAuthFlow()
.authorizationUrl("http://localhost:8080/realms/myrealm/protocol/openid-connect/auth")
.tokenUrl("http://localhost:8080/realms/myrealm/protocol/openid-connect/token")
.scopes(new Scopes().addString("openid", "OpenID scope"))
)
)
))
.addSecurityItem(new SecurityRequirement().addList("keycloak_oauth"));
}