Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Spreadsheet with a service account

I want to access a spreadsheet on Google Drive by using de java Google spreadsheet API. In the past i used the client login method to login but this method is deprecated now. Now I'm trying to use a service account to getting authenticated without interaction with the user because the tool is running in the background i needs to be automated. But i can't get it working. These my code now.

    List<String> SCOPES_ARRAY = Arrays.asList(
            "https://www.googleapis.com/auth/drive.file",
            "https://www.googleapis.com/auth/userinfo.email",
            "https://www.googleapis.com/auth/userinfo.profile",
            "https://docs.google.com/feeds",
            "https://spreadsheets.google.com/feeds");
    credential = new GoogleCredential.Builder()
                .setTransport(transport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(
                        "[email protected]")
                .setServiceAccountScopes(SCOPES_ARRAY)
                .setServiceAccountPrivateKeyFromP12File(p12)
                .setServiceAccountUser("[email protected]")
                .build();
    service = new SpreadsheetService("MonitorV3");
    service.setOAuth2Credentials(credential);

    SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");

    worksheetFeed = service.getFeed(spreadsheet.getWorksheetFeedUrl(),
                    WorksheetFeed.class);

But i'm getting a nullpointerexception when executing the last line. something goes wrong with refresh token. Is there someone seeing what i'm doing wrong?enter image description here

I made a standalone simple application and now I get following detailded error:

Exception in thread "main" com.google.gdata.util.AuthenticationException: Failed to refresh access token: 401 Unauthorized
at com.google.gdata.client.GoogleAuthTokenFactory$OAuth2Token.refreshToken(GoogleAuthTokenFactory.java:260)
at com.google.gdata.client.GoogleAuthTokenFactory.handleSessionExpiredException(GoogleAuthTokenFactory.java:702)
at com.google.gdata.client.GoogleService.handleSessionExpiredException(GoogleService.java:738)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:649)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at JavaApplication20.printDocuments(JavaApplication20.java:50)
at main.main(main.java:35)
like image 952
jackiejarvis Avatar asked Jan 08 '23 00:01

jackiejarvis


2 Answers

GoogleCredential is currently deprecated. Instead, if you need to access Google Sheets using a service account, use the Google OAuth2 library.

Usage example:

// A few common declarations:
private static final String APPLICATION_NAME = "My Google Sheets Application";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);

// Initializing the service:
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredentials googleCredentials;
try(InputStream inputSteam = <YOURCLASS>.class.getResourceAsStream("/path/to/credentials/file.json")) {
  googleCredentials = GoogleCredentials.fromStream(credentialsStream).createScoped(SCOPES)
}
Sheets service = Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpCredentialsAdapter(googleCredentials))
            .setApplicationName(APPLICATION_NAME)
            .build()
like image 52
Itay Polack-Gadassi Avatar answered Jan 10 '23 15:01

Itay Polack-Gadassi


I fixed this by using following code:

credential = new GoogleCredential.Builder()
            .setTransport(transport)
            .setJsonFactory(jsonFactory)
            .setServiceAccountId("618982716759-9ele96d95b7gqar6tn2ofa7jrjrudlol@developer.gserviceaccount.com")
            .setServiceAccountPrivateKeyFromP12File(p12)
            .setServiceAccountScopes(SCOPES_ARRAY).build();
            credential.refreshToken();

So without the .setServiceAccountUser("[email protected]"). Now it's working without any errors.

like image 22
jackiejarvis Avatar answered Jan 10 '23 14:01

jackiejarvis