Search code examples
google-app-engineflaskpostmanservice-accounts

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


Below are my requirements.

  • Develop a flask app.
  • Use collections in the firebase in the app.
  • Deploy this app on Google App Engine using a standard service account

What I have done.

  • Created a service account
  • Downloaded the corresponding credentials json; I am calling it as key.json
  • written a 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

I have tested this locally and also on deployed on Google App Engine.

In both the cases, key.json was in the same directory as the code. I have verified that if this key.json is modified to store wrong data, then /users endpoint won't work and gives me a 500 error.

So far so good. I want to know if this is even the right approach.

  • I want the key.json authentication to applied even for the root / endpoint. i.e., if the user supplies a valid key.json, only then the Welcome to my first app should be displayed. Else, Unauthorized user message needs to be displayed.

Solution

  • As mentioned by @Gaefan and @DishantMakwana, as well as in this documentation:

    An API key only identifies the application and doesn't require user authentication. It is sufficient for accessing public data.

    So in order to authenticate/authorize your users you should reconsider your strategy. I would recommend you to follow the instructions in the Authenticating as an end user Documentation.