Swagger在Linux服务器上如何配置安全认证
导读:在 Linux 服务器上配置 Swagger 安全认证 总体思路 在 Swagger/OpenAPI 规范中声明安全方案(如 API Key、HTTP Basic、OAuth 2.0/OpenID Connect),并在需要的 paths...
在 Linux 服务器上配置 Swagger 安全认证
总体思路
- 在 Swagger/OpenAPI 规范中声明安全方案(如 API Key、HTTP Basic、OAuth 2.0/OpenID Connect),并在需要的 paths 上启用。
- 在服务端或反向代理层落地校验逻辑:应用内校验(如 Spring Security、JWT 过滤器)或网关层校验(如 Nginx/Apache 的 Basic Auth)。
- 通过 HTTPS 暴露文档,避免凭据泄露;为 Swagger UI 与后端接口设置一致的认证方式或按路径区分访问控制。
常见方案与落地示例
- API Key(请求头)
- 规范示例(OpenAPI 2.0):
swagger: '2.0' info: title: Sample API version: 1.0.0 securityDefinitions: ApiKeyAuth: type: apiKey name: Authorization in: header paths: /users: get: security: - ApiKeyAuth: [] - 服务端校验思路:在中间件/过滤器读取请求头 Authorization 并校验签名或白名单。Node.js 示例:
app.use((req,res,next)=> { const key = req.headers['authorization']; if (key === 'your-secret-api-key') next(); else res.status(401).send('Unauthorized'); } );
- 规范示例(OpenAPI 2.0):
- HTTP Basic
- 规范示例:
securityDefinitions: BasicAuth: type: basic paths: /users: get: security: - BasicAuth: [] - 服务端校验思路:启用 HTTP Basic 认证;Spring Security 示例:
http.authorizeRequests() .antMatchers("/swagger-ui.html","/swagger-resources/**","/v2/api-docs").authenticated() .and().httpBasic();
- 规范示例:
- OAuth 2.0 / OpenID Connect
- 规范示例(accessCode 流程):
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] - 服务端校验思路:接入 OAuth2 授权服务器(如 Keycloak、Auth0),在 Swagger UI 中配置 authorizationUrl/tokenUrl 与 scopes,后端按令牌与范围校验。
- 规范示例(accessCode 流程):
反向代理与网关层保护
- 使用 Nginx 为 Swagger UI 路径启用 Basic Auth(适合快速上线与最小改造):
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 - 使用 Apache 亦可实现相同效果(基于 mod_auth_basic 与 ProxyPass)。
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> - 声明安全方案(Basic 示例):
@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} )); } - 若采用 API Key,可在过滤器中读取 X-API-KEY 并构造认证对象,或在网关层统一校验。
生产环境注意事项
- 全程使用 HTTPS,禁用明文端口;为文档与业务接口分别配置合适的 CORS 与缓存策略。
- 对 Swagger UI 路径实施与业务接口一致的访问控制;必要时仅内网开放文档,或通过 Nginx/Apache 做 Basic Auth 或 IP 白名单。
- 避免在客户端代码中硬编码密钥/令牌;为 OAuth2 配置合适的 scopes 与 redirect_uris,并在 UI 中正确填写 authorizationUrl/tokenUrl。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Swagger在Linux服务器上如何配置安全认证
本文地址: https://pptw.com/jishu/763291.html
