CentOS环境下Swagger权限管理的实现方法
在CentOS服务器上,Swagger本身不直接提供权限管理功能,需通过身份验证+授权机制结合后端服务实现。以下是具体实施方案:
确保CentOS服务器已安装Java(1.8及以上)、Maven、Swagger相关依赖(如springfox-swagger2、springfox-swagger-ui)及Web服务器(如Nginx、Apache)。若未安装,可通过以下命令快速部署基础环境:
# 安装Java
sudo yum install java-1.8.0-openjdk-devel -y
# 安装Maven
sudo yum install maven -y
# 安装Nginx(可选,用于反向代理)
sudo yum install nginx -y
Spring Security是Java生态中最常用的安全框架,可与Swagger无缝集成,实现登录认证和权限控制。
在Spring Boot项目的pom.xml中添加Spring Security和Swagger相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<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>
创建SecurityConfig类(继承WebSecurityConfigurerAdapter),定义认证方式(如内存认证、数据库认证)和授权规则(哪些路径需要认证):
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 配置认证逻辑(此处为内存认证,生产环境建议用数据库)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin123").roles("ADMIN") // {noop}表示不加密密码(仅测试用)
.and()
.withUser("user").password("{noop}user123").roles("USER");
}
// 配置授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 关闭CSRF(简化配置,生产环境建议开启)
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v2/api-docs/**").authenticated() // Swagger相关路径需认证
.anyRequest().permitAll() // 其他请求允许匿名访问
.and()
.httpBasic(); // 使用HTTP Basic认证(弹出登录框)
}
// 配置JWT解码器(若用JWT,需取消注释并实现)
/*
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withJwkSetUri("https://your-auth-server/.well-known/jwks.json").build();
}
*/
}
创建SwaggerConfig类(继承Docket),定义API文档的扫描范围:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) // 扫描controller包
.paths(PathSelectors.any())
.build();
}
}
Nginx可作为反向代理服务器,为Swagger UI添加HTTP Basic认证或IP限制,进一步提升安全性。
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
# 安装htpasswd工具(用于生成密码文件)
sudo yum install httpd-tools -y
# 创建密码文件(首次创建需用-c参数,后续添加用户无需-c)
sudo htpasswd -c /etc/nginx/.htpasswd admin
# 输入密码(如admin123)
编辑/etc/nginx/nginx.conf,添加以下内容:
server {
listen 80;
server_name yourdomain.com; # 替换为你的域名或IP
location /swagger-ui.html {
auth_basic "Restricted Access"; # 认证提示信息
auth_basic_user_file /etc/nginx/.htpasswd; # 密码文件路径
proxy_pass http://localhost:8080/swagger-ui.html; # 反向代理到后端服务
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 可选:限制IP访问
# location /swagger-ui.html {
# allow 192.168.1.100; # 允许的IP
# deny all; # 拒绝其他IP
# proxy_pass http://localhost:8080/swagger-ui.html;
# }
}
sudo systemctl restart nginx
若需不同角色访问不同API,需在后端服务中实现RBAC逻辑,并在Swagger中标记角色权限。
修改SecurityConfig,添加角色授权规则:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v2/api-docs/**").authenticated()
.antMatchers("/api/admin/**").hasRole("ADMIN") // 仅ADMIN角色可访问/admin路径
.antMatchers("/api/user/**").hasAnyRole("USER", "ADMIN") // USER和ADMIN角色可访问/user路径
.anyRequest().permitAll()
.and()
.httpBasic();
}
在swagger.yaml中,通过securityDefinitions和security字段标记角色权限:
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
components:
securitySchemes:
bearerAuth:
type: oauth2
flows:
password:
tokenUrl: https://your-auth-server/oauth/token
scopes:
read: Grants read access
write: Grants write access
security:
- bearerAuth: [] # 全局应用bearer认证
paths:
/api/admin/users:
get:
summary: Get all users (Admin only)
security:
- bearerAuth: ["ADMIN"] # 仅ADMIN角色可访问
responses:
'200':
description: OK
/api/user/profile:
get:
summary: Get user profile (User/Admin)
security:
- bearerAuth: ["USER", "ADMIN"] # USER和ADMIN角色可访问
responses:
'200':
description: OK
mvn spring-boot:run
http://yourdomain.com/swagger-ui.htmlhttp://localhost:8080/swagger-ui.htmladmin/admin123),验证是否能访问Swagger文档。/api/admin/users(需ADMIN角色)和/api/user/profile(需USER/ADMIN角色),验证角色权限是否生效。{noop})。MethodSecurity(如@PreAuthorize注解)。