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?