在 Flask 应用程序中使用 Google 服务帐户进行身份验证并在 Google App Engine 上部署

Authentication using Google Service Account in a flask app and deploying on Google App Engine

以下是我的要求。

我做了什么

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 错误。

到目前为止一切顺利。我想知道这是否是正确的方法。

正如@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 管理。很有魅力。