0
votes

I have an application that uses Google APIs. I created a service account for it, downloaded the keys and enabled domain-wide delegation for GSuite. The scopes include Drive. I'm trying to iterate through the Drive files of GSuite users by using the service account to impersonate the users like this:

final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

GoogleCredential.Builder builder = new GoogleCredential.Builder()
    .setTransport(HTTP_TRANSPORT)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId(serviceAccountEmail)            
    .setServiceAccountPrivateKey(credFromJson(HTTP_TRANSPORT).getServiceAccountPrivateKey())
    .setServiceAccountScopes(SCOPES);
builder.setServiceAccountUser(userEmail);

GoogleCredential credential = builder.build();

return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, null)
                .setApplicationName(APPLICATION_NAME)
                .setHttpRequestInitializer(credential).build();

The GoogleCredential is created successfully. It has serviceAccountId, serviceAccountPrivateKey, serviceAccountUser and the needed scopes.

However when calling

driveService.files().list().setFields("nextPageToken, files(*)").execute().getFiles();

I get 401 Unauthorized error. I'm fairly sure that all the steps rearding the service account have been completed successfully, and domain-wide delegation is enabled, and even the credential seems okay. The scopes are certainly correct. Where should I look next?

details

1

1 Answers

0
votes

401 Unauthorized error.

Means you dont have access. Why you dont have access is another question. It could be the delegation setup or it could be your authentication.

Have you tried doing a file.list on the service accounts own account to see if its working at all. That will tell you if its an issue with your authorization or if its the gsuite setup.

But it looks to me like your not even setting credentials which will never work.

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(DriveScopes.all());

    // Construct the Analytics Reporting service object.
    return new Drive.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();