How to setup google app script web app endpoint authorisation with google service account?
First i have a webapp in google app script:
function doGet() {
boolResult = isDailyGmailCountLargerThan10()
console.log(boolResult)
if(boolResult) return ContentService.createTextOutput('Done');
else return ContentService.createTextOutput('Error');
}
function isDailyGmailCountLargerThan10(){
intCount = GmailApp.search("newer_than:1d").length;
if (intCount>10) return true
else return false
}
And then I have below python script to make the request:
import requests
url="https://script.google.com/a/macros/<my_project>/s/<my_script_id>/exec"
r=requests.get(url)
print(r.status_code)
print(r.text)
Unfortunately, as only i can access and execute the script (which means I setup like this Execute as [Me] | Who has access [Me]), it return me with either the login page or unauthorised access.
Thus, I rewrite the python as below:
from google.oauth2 import id_token
from google.oauth2 import service_account
import google.auth
import google.auth.transport.requests
from google.auth.transport.requests import AuthorizedSession
cred_path = '/path/to/key.json'
target_audience = 'https://script.google.com/a/macros/<my_project>/s/<my_script_id>/exec'
url = 'https://script.google.com/a/macros/<my_project>/s/<my_script_id>/exec'
creds = service_account.IDTokenCredentials.from_service_account_file(
cred_path,
target_audience=target_audience)
authed_session = AuthorizedSession(creds)
# make authenticated request and print the response, status_code
resp = authed_session.get(url)
print(resp.status_code)
print(resp.text)
# Returned 401 | Unauthorized
# to verify an ID Token
request = google.auth.transport.requests.Request()
token = creds.token
print(token)
print(id_token.verify_token(token,request))
Unfortunately, it returned 401 Unauthorized. So here is my question:
How to use google service account to pretent as me before sending get request the the google app script the only authorised user is me? I cannot find any reference to grant permission to google service account email to sending request to my google app script.