我在让我的 API 仅使用 API 密钥身份验证时遇到了一些问题。 我已经为一个简单的 Flask API 部署了一个 Cloud Run 应用程序,该 API 返回“hello world”,需要身份验证。 然后,我在 API 网关上创建了一个 API,其中的 API 配置指定使用 API 密钥。 我怀疑 API 配置中有一个我没有看到的错误,导致无需 API 密钥即可访问 API。 指定禁止未经身份验证的请求后,直接访问应用程序 URL (https://flask-test-abcd1234.a.run.app/hi) 将按预期返回“Error: Forbidden”。 但是,API 网关 URL (https://gatename-abcde123.nw.gateway.dev/hi) 将返回 API 响应,无需向 URL 添加 ?api_key= 查询。 任何帮助是极大的赞赏。 编辑:我还创建了一个具有云运行调用者角色的服务帐户。
部署的云运行应用程序:
from flask import Flask
app = Flask(__name__)
@App.route('/hi', methods=['GET'])
def hello_world():
return 'Hello, World?'
if __name__ == '__main__':
app.run(debug=True)
API 配置 .yaml 文件:
# openapi2-run.yaml
swagger: "2.0"
info:
title: Sample Flask API d
description: A simple API for demonstration
version: 1.0.0
host: test-api.apigateway.projectname.cloud.goog
schemes:
- https
produces:
- application/json
security:
- api_key: []
x-google-backend:
address: >-
https://test-abcd1234-nw.a.run.app
x-google-management:
metrics:
- name: "get-requests"
displayName: "get requests"
valueType: INT64
metricKind: DELTA
quota:
limits:
- name: "get-limit"
metric: "get-requests"
unit: "1/min/{project}"
values:
STANDARD: 1000
paths:
/hi:
get:
summary: Get hello
operationId: getHi
security: []
parameters: []
responses:
200:
description: A successful response
schema:
type: string
securityDefinitions:
api_key:
type: apiKey
name: key
in: query
definitions:
User:
type: object
properties:
username:
type: string
firstname:
type: string
lastname:
type: string
email:
type: string
yaml
文件复制了您的问题,并且我得到了相同的行为。 我已经更新了您的配置文件的一部分,现在只有在使用 URL 添加 API 密钥作为查询时才能访问该页面,即
?key=API_KEY
。这是更新的部分
paths:
/hi:
get:
summary: Get hello
operationId: getHi
security:
- api_key: []
x-google-quota:
metricCosts:
"get-requests": 1
parameters: []
responses:
200:
description: "successful operation"
schema:
type: "array"
items:
$ref: "#/definitions/User"