在 Flask 应用程序中使用 Google 服务帐户进行身份验证并在 Google App Engine 上部署
Authentication using Google Service Account in a flask app and deploying on Google App Engine
以下是我的要求。
- 开发一个 Flask 应用程序。
- 在应用程序中使用 firebase 中的集合。
- 使用标准服务帐户在 Google App Engine 上部署此应用程序
我做了什么
- 创建了一个服务帐户
- 下载了相应的凭据json;我称它为 key.json
- 写了一个main.py
cred = credentials.Certificate('key.json')
default_app = initialize_app(cred)
db = firestore.client()
user_ref = db.collection_group('Users')
@app.route('/', methods=['GET'])
def home():
return "<h1>Welcome to my first app</h1>"
@app.route('/users', methods=['GET'])
def getUsers():
try:
result = [user.to_dict() for user in user_ref .stream()]
return jsonify(result), 200
except Exception as e:
result = { "message:"failed"}
return jsonify(result), 500
我已经在本地进行了测试,还在 Google App Engine 上进行了部署。
在这两种情况下,key.json 与代码位于同一目录中。
我已经验证如果此 key.json 被修改为存储错误数据,那么 /users 端点将无法工作并给我一个 500 错误。
到目前为止一切顺利。我想知道这是否是正确的方法。
- 我希望 key.json 身份验证甚至适用于根/端点。
即,如果用户提供了有效的 key.json,则只应显示
Welcome to my first app
。
否则,需要显示 Unauthorized user
消息。
正如@Gaefan 和@DishantMakwana 所提到的,以及在此 documentation:
An API key only identifies the application and doesn't require user authentication. It is sufficient for accessing public data.
因此,为了 authenticate/authorize 您的用户,您应该重新考虑您的策略。我建议您按照 Authenticating as an end user Documentation.
中的说明进行操作
我发现我们可以使用 Google Cloud Endpoints 进行 API 管理。很有魅力。
以下是我的要求。
- 开发一个 Flask 应用程序。
- 在应用程序中使用 firebase 中的集合。
- 使用标准服务帐户在 Google App Engine 上部署此应用程序
我做了什么
- 创建了一个服务帐户
- 下载了相应的凭据json;我称它为 key.json
- 写了一个main.py
cred = credentials.Certificate('key.json') default_app = initialize_app(cred) db = firestore.client() user_ref = db.collection_group('Users') @app.route('/', methods=['GET']) def home(): return "<h1>Welcome to my first app</h1>" @app.route('/users', methods=['GET']) def getUsers(): try: result = [user.to_dict() for user in user_ref .stream()] return jsonify(result), 200 except Exception as e: result = { "message:"failed"} return jsonify(result), 500
我已经在本地进行了测试,还在 Google App Engine 上进行了部署。
在这两种情况下,key.json 与代码位于同一目录中。 我已经验证如果此 key.json 被修改为存储错误数据,那么 /users 端点将无法工作并给我一个 500 错误。
到目前为止一切顺利。我想知道这是否是正确的方法。
- 我希望 key.json 身份验证甚至适用于根/端点。
即,如果用户提供了有效的 key.json,则只应显示
Welcome to my first app
。 否则,需要显示Unauthorized user
消息。
正如@Gaefan 和@DishantMakwana 所提到的,以及在此 documentation:
An API key only identifies the application and doesn't require user authentication. It is sufficient for accessing public data.
因此,为了 authenticate/authorize 您的用户,您应该重新考虑您的策略。我建议您按照 Authenticating as an end user Documentation.
中的说明进行操作我发现我们可以使用 Google Cloud Endpoints 进行 API 管理。很有魅力。