1
service_account_mail = 'xxxxxx@developer.gserviceaccount.com'
service_account_client_id = 'xxxxxx.apps.googleusercontent.com'

with open("private_key.p12") as f:
    private_key = f.read()

gapps_scope=[
    'https://www.googleapis.com/auth/drive',
    'https://apps-apis.google.com/a/feeds/emailsettings/2.0/',
]

credentials = SignedJwtAssertionCredentials(service_account_mail, private_key, gapps_scope)

print credentials.access_token
None

credentials.get_access_token()

credentials.access_token
Now I get something useful

headers = {
    'Authorization': 'Bearer ' + credentials.access_token,
    'Content-type': 'application/atom+xml'
}

url_tpl = """https://apps-apis.google.com/a/feeds/emailsettings/2.0/mydomain.com/%s/%s"""

url = url_tpl % (myusername, 'label')
r = requests.get(url, headers=headers)
403 - 'You are not authorized to access this API.'

body_tpl = """<?xml version="1.0" encoding="utf-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">
    <apps:property name="signature" value="%s" />
</atom:entry>"""

url = url_tpl % (myusername, 'signature')

payload = body_tpl % 'Test'
r = requests.put(url, headers=headers, data=payload)
403 - 'You are not authorized to access this API.'

r = requests.get(url, headers=headers)
403 - 'You are not authorized to access this API.'

drive_url = "https://www.googleapis.com/drive/v2/files"
headers = {  'Authorization': 'Bearer ' + credentials.access_token, }
r = requests.get(drive_url, headers=headers)
200 - 'OK'

还尝试过:EmailSettingsClient + AuthSubToken、EmailSettingsClient + client.auth_token 覆盖、EmailSettingsClient + HttpRequest(headers=additional_headers)、EmailSettingsClient + OAuth2TokenFromCredentials(credentials).authorize

当我在步骤 2 中直接在 OAuth 2.0 Playground 中使用我的服务帐户的 credential.access_token 时,我确实得到了相同的结果。也就是说,它适用于 Drive,但不适用于 EmailSettings。

其他人能否确认它有效(请通过实际尝试)并解释我在这里做错了什么?

非常感谢。

4

0 回答 0