Authentification de compte de Service d'accès API Java Google Contacts


J'essaie d'accéder à Googles Contacts API mais ma tentative a déjà échoué lors de l'autorisation. D'autres langages (web), je suis habitué à l'APIConsole et à la clé API publique (autorisation).

GoogleCredential credential = new GoogleCredential().setAccessToken("<<PublicAPIKey>>");
System.out.println(credential.refreshToken());          // false

De cette façon, je ne peux pas actualiser le jeton et ne suis pas sûr d'utiliser la clé publique comme accesstoken... Au lieu de cela, j'ai essayé sur un compte de service :

private static final String USER_ACCOUNT_EMAIL = "[email protected]";
private static final String SERVICE_ACCOUNT_EMAIL = "[email protected]";
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "xy.p12";

public App() {
    Set<String> scopes = new HashSet<String>();
    scopes.add("https://www.google.com/m8/feeds");

    try {
        GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(new NetHttpTransport())
            .setJsonFactory(new JacksonFactory())
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountScopes(scopes)
            .setServiceAccountUser(USER_ACCOUNT_EMAIL)
            .setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
            .build();

        System.out.println(credential.refreshToken());
        //System.out.println(credential.getAccessToken());
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Voici mon exception:

com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
        at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
        at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
        at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
        at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
        at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
        at App.<init>(App.java:50)
        at App.main(App.java:29)

Merci pour un indice!

Author: Stephan Celis, 2015-04-30

1 answers

Sans appeler setServiceAccountUser() mon code a parfaitement fonctionné. Mais vous aurez juste un compte usurpé (service_account_mail) pas vos contacts personnels.

Une autre source possible pour une exception "401 Unauthorized" est de laisser le credential.refreshToken() de côté. L'appel est nécessaire pour écrire le code d'accès dans la référence.

Sous la classe finie:

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.gdata.client.contacts.ContactsService;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class Connector {

  private static ContactsService contactService = null;
  private static HttpTransport httpTransport;

  private static final String APPLICATION_NAME = "Your-App/1.0";
  private static final String SERVICE_ACCOUNT_EMAIL = "[email protected]";

  private Connector() {
    // explicit private no-args constructor
  }

  public static ContactsService getInstance() {
    if (contactService == null) {
      try {
        contactService = connect();

      } catch (GeneralSecurityException | IOException e) {
        e.printStackTrace();
      }
    }

    return contactService;
  }

  private static ContactsService connect() throws GeneralSecurityException, IOException {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    // @formatter:off
    GoogleCredential credential = new GoogleCredential.Builder()
                                            .setTransport(httpTransport)
                                            .setJsonFactory(JacksonFactory.getDefaultInstance())
                                            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                                            .setServiceAccountScopes(Collections.singleton("https://www.google.com/m8/feeds"))
                                            .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
                                            .build();
    // @formatter:on

    if (!credential.refreshToken()) {
      throw new RuntimeException("Failed OAuth to refresh the token");
    }

    ContactsService myService = new ContactsService(APPLICATION_NAME);
    myService.setOAuth2Credentials(credential);
    return myService;
  }

}
 0
Author: binzram, 2015-04-30 16:33:09