5

I want to use Java Google Drive API. I tried this code:

public Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException
    {
        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory JSON_FACTORY = new JacksonFactory();

        GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId("sonoratestw-226@sonora-project.iam.gserviceaccount.com")
            .setServiceAccountPrivateKeyFromP12File(new java.io.File("C:\\buffer\\sonora project-3256770463ed.p12"))
            .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN))
            .setServiceAccountUser("sonoratestw@gmail.com")
            .build();

        Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, null)
            .setApplicationName("FileListAccessProject")
            .setHttpRequestInitializer(credential).build();

        return service;
    }

But I get this error:

An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized

I use this configuration:

enter image description here

Can you give some idea how I can fix this?

Peter Penzov
  • 2,352
  • 100
  • 358
  • 675
  • I don't think you can use setServiceAccountUser unless its a domain admin account and you have added the service account to the admin account and the user in question is also a user on the admin account. – DaImTo Dec 09 '16 at 13:57
  • Can you give the total error and exception it is throwing? – Coder Dec 09 '16 at 18:17
  • Have you found the solution? Please provide your answer. – Satheeshkumar Dec 05 '19 at 05:57

1 Answers1

0

Based on this SO question, one reason that you get the error 401 is that the service account you are using doesn't have access to the drive account associated with your Gmail address. So if you want to be able to access the files it uploads you must grant yourself access to them though the service account.

Here are the other SO questions that I think can help you to understand more the service account

Community
  • 1
  • 1
KENdi
  • 7,670
  • 2
  • 15
  • 27