I build this very simple code, very similar to the tutorial here. I simply use the default credential, instead of using a service account key file (I can explain why if required, but in short, it's not secured!)
To test it, simply change the sheet ID in the code
import os
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def test_sheet():
from googleapiclient.discovery import build
import google.auth
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
credentials, project_id = google.auth.default(scopes=SCOPES)
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1oHzQLk79_TeEZtQyTLxk47PKDi7g1oy1O0MgSHzhUSk'
SAMPLE_RANGE_NAME = 'A1:C1'
service = build('sheets', 'v4', credentials=credentials)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Results:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print(row)
return row[0] + ',' + row[1], 200
if __name__ == "__main__":
app.run(host='0.0.0.0',port=int(os.environ.get('PORT',8080)))
Anyway, here my problem:
- When I deploy it on Cloud Run, and I authorize the Cloud Run custom service account (without key, I use the application default credential) on my spreadsheet, it works
- When, locally, I use a service account key file of the Cloud Run that I set in the
GOOGLE_APPLICATION_CREDENTIALS
, it works (bad practice as I said in introduction) - When, locally, I use my user credentials authorized on my sheet (gather with
gcloud auth application-default login
) it doesn't work with this error: 403.......Request had insufficient authentication scopes. - When I deploy on App Engine, and I authorize the AppEngine default service account (<PROJECT_ID>@appspot.gserviceaccount.com), it doesn't work with this error: 403.......Request had insufficient authentication scopes.
QUESTIONS
- Why I can't change the scope of the user account credential? I could understand this case. I can't invoke private Cloud Function and private Cloud Run with my user credential. Why not another limitation!
- Why I can't change the scope of the App Engine default service account? Here I don't catch the differences with the other service accounts on GCP