Sayali
Sayali

Reputation: 366

Google Contacts - Get contacts of another user using service account

I am trying to get contacts of another user using Google Service Account. I even set the user credentials to the username and password of the account for which I want to fetch the contacts. However, I keep getting an error - Exception in thread "main" com.google.gdata.util.ServiceForbiddenException: Cannot request contacts belonging to another user

Initially I was using admin account to get the contacts of another user for which I kept getting a Forbidden error. I was told that service accounts will work in this case.

Can anybody please help? Is it really possible to get the contacts of another account with service accounts or any other method? If yes, any idea why I must be getting this error?

Upvotes: 2

Views: 1840

Answers (2)

rhopman
rhopman

Reputation: 848

If you want to access a user's contacts using a service account, you need to do three things (see https://developers.google.com/accounts/docs/OAuth2ServiceAccount):

  1. Create a service account in the Google Developers Console.
  2. Delegate domain-wide authority to the service account using the domain’s Admin console.
  3. (Necessary to access contacts:) Impersonate the user by specifying the email address of the user account with the setServiceAccountUser method of the GoogleCredential factory.

For example:

GoogleCredential credential = new GoogleCredential.Builder()
  .setTransport(httpTransport)
  .setJsonFactory(JSON_FACTORY)
  .setServiceAccountId(emailAddress)
  .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12"))
  .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN))
  .setServiceAccountUser("[email protected]")
  .build();

The error message Cannot request contacts belonging to another user suggests that you forgot the last step.

Upvotes: 1

Arun Nagarajan
Arun Nagarajan

Reputation: 5645

You can only get access to other people's contacts using Service Accounts if your Service Account client gets white listed at the domain level. In other words - you can't arbitrarily get others' contacts across domain boundaries without some admin access.

The simplest option is to use the OAuth 2 web server or client side flows - where each user has to authorize your data access.

Upvotes: 0

Related Questions