在CentOS上進行Swagger測試前,需根據測試方式安裝對應工具:
sudo yum install docker && sudo systemctl start docker
);若通過Node.js安裝,需安裝Node.js和npm(參考搜索結果中centos swagger兼容性測試
部分)。sudo yum install java-1.8.0-openjdk-devel
)和Maven(sudo yum install maven
)。根據項目類型選擇以下方式部署Swagger:
Docker快速部署(推薦):
拉取Swagger UI鏡像并運行容器,直接訪問界面:
docker pull swaggerapi/swagger-ui:v4.15.5 # 拉取最新鏡像
docker run -d -p 8080:8080 -e SWAGGER_FILE=/app/swagger.json -v /path/to/your/swagger.json:/app/swagger.json swaggerapi/swagger-ui:v4.15.5 # 掛載本地文檔
瀏覽器訪問http://<CentOS-IP>:8080
即可查看Swagger UI。
Spring Boot項目集成(自動生成文檔):
在pom.xml
中添加Swagger依賴:
<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>
創建配置類啟用Swagger:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any()) // 掃描所有接口
.paths(PathSelectors.any()) // 匹配所有路徑
.build();
}
}
啟動項目后,訪問http://<CentOS-IP>:8080/swagger-ui.html
查看自動生成的文檔。
Swagger UI提供了可視化的接口測試功能,步驟如下:
/user/query
)。limit
、page
)。若習慣使用命令行,可通過curl模擬HTTP請求測試接口:
curl "http://<CentOS-IP>:8080/api/users?limit=10&page=1"
curl -X POST "http://<CentOS-IP>:8080/api/user/add" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=test&password=123456"
curl -X POST "http://<CentOS-IP>:8080/api/user/update" \
-H "Content-Type: application/json" \
-d '{"id":1,"name":"New Name","email":"new@example.com"}'
執行后,終端會返回接口的響應結果(如狀態碼、JSON數據)。為確保接口安全性,可使用以下工具進行擴展測試:
swagger-hacker.py
腳本探測接口可用性及潛在漏洞(如未授權訪問):python3 swagger-hacker.py -u http://<CentOS-IP>:8080/swagger-ui.html