1

I am trying to build a Gmail service which will read a user's emails, once their IT admin has authenticated the App on the Apps marketplace. From the documentation, it seemed service accounts would be the right fit, for which I tried both:

    scope = "https://www.googleapis.com/auth/gmail.readonly"
    project_number = "c****io"
    authorization_token, _ = app_identity.get_access_token(scope)
    logging.info("Using token %s to represent identity %s",
                 authorization_token, app_identity.get_service_account_name())
    #authorization_token = "OAuth code pasted from playground"
    response = urlfetch.fetch(
        "https://www.googleapis.com/gmail/v1/users/me/messages",
        method=urlfetch.GET,
        headers = {"Content-Type": "application/json",
                   "Authorization": "OAuth " + authorization_token})

and

    credentials = AppAssertionCredentials(scope=scope)
    http = credentials.authorize(httplib2.Http(memcache))
    service = build(serviceName='gmail', version='v1', http=http)
    listReply = gmail_service.users().messages().list(userId='me', q = '').execute()

I then started dev_appserver.py as per Unable to access BigQuery from local App Engine development server

However, I get an HTTP error code 500 "Backend Error". Same code, but when I paste the access_token from the OAuth playground, it works fine (HTTP 200). I'm on my local machine in case that makes any difference. Wondering if I'm missing anything? I'm trying to find all emails for all users of a particular domain where their IT admin has installed my Google Marketplace App.

Thanks for the help!

Community
  • 1
  • 1
Debnath Sinha
  • 1,087
  • 1
  • 12
  • 25

1 Answers1

0

To do this type of impersonation, you should create a JWT and set the "sub" field to the email address of the user whose mailbox you want to access. Developer documentation: Using OAuth 2.0 for Server to Server Applications: Additional claims.

The python code to construct the credentials will look something like

credentials = SignedJwtAssertionCredentials(
    "<service account email>@developer.gserviceaccount.com",
    file("secret-privatekey.pem", "rb").read(),
    scope=["https://www.googleapis.com/auth/gmail.readonly"],
    sub="<user to impersonate>@your-domain.com"
)
  • Thanks! So in the context of a Google Apps Marketplace app (which we are building), this should work for any domain that has installed the app? Also, I noticed you can create multiple service accounts...would this work for any of the (SERVICE_ACCOUNT_EMAIL, private_key.p12) combinations? I ask because many of the Domain Wide Auth Delegation docs talk about "AdminConsole:Manage third party OAuth Client access" but not the case of a Marketplace App. And when I install the app on my domain using "Test Install Flow", the API client access shows the app name and not the service account email. – Debnath Sinha Jul 24 '14 at 15:21