GCP云函数Swagger(OpenAPI2.0)添加Firebase Auth后API Key验证失效
解决Google Cloud Function API同时支持API Key和Firebase Auth的OpenAPI 2.0配置问题
你的问题核心是OpenAPI 2.0的security配置逻辑被Google Cloud Endpoints误判为同时需要两种认证(AND),而非你期望的二选一(OR),再加上Firebase OAuth2配置中的冗余字段可能引发逻辑冲突,导致API Key认证失效。
解决步骤:
1. 修正security配置的逻辑结构
虽然你当前根级的security写法在OpenAPI规范中是OR逻辑,但Cloud Endpoints对根级配置的处理可能存在偏差,建议将认证配置移到接口操作级别,明确指定二选一规则:
paths: /: get: # 保留原有其他配置 security: - api_key: [] # 允许使用API Key认证 - firebase: [] # 允许使用Firebase JWT认证
2. 清理Firebase认证的冗余配置
你的Firebase securityDefinitions中包含标准OAuth2的authorizationUrl和flow字段,但Cloud Endpoints是通过x-google-*扩展字段处理Firebase认证的,这些冗余字段可能干扰认证逻辑判断,建议删除:
securityDefinitions: firebase: type: "oauth2" x-google-issuer: "https://securetoken.google.com/<PROJECT_ID>" x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com" x-google-audiences: "<PROJECT_ID>" # 移除 authorizationUrl: "" 和 flow: "implicit"
3. 完整修正后的配置示例
swagger: "2.0" info: title: <Title> description: <Desc> version: 1.0.0 schemes: - https produces: - application/json paths: /: get: summary: Info about the API-status operationId: app x-google-backend: address: https://<REGION>-<PROJECT_ID>.cloudfunctions.net/app security: - api_key: [] - firebase: [] responses: "200": description: A successful response schema: type: string securityDefinitions: api_key: type: "apiKey" name: "key" in: "query" firebase: type: "oauth2" x-google-issuer: "https://securetoken.google.com/<PROJECT_ID>" x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com" x-google-audiences: "<PROJECT_ID>"
4. 验证部署与测试
- 重新部署修正后的OpenAPI配置到Cloud Endpoints
- 分别测试两种认证方式:
- API Key请求:
curl "https://<你的Endpoints域名>/?key=<你的API Key>" - Firebase JWT请求:
curl "https://<你的Endpoints域名>/" -H "Authorization: Bearer <Firebase生成的JWT>"
- API Key请求:
关键说明
OpenAPI 2.0中,security数组的每个元素代表一组独立的认证要求,数组内的元素是OR逻辑(满足任一即可);如果将多个认证方案放在同一个元素内,则是AND逻辑(需同时满足)。Cloud Endpoints对操作级别的security配置逻辑解析更准确,因此移到操作级别可避免根级配置的潜在问题。
内容的提问来源于stack exchange,提问作者Frostman
相关产品推荐
相关产品推荐

