Error with OAuth2 authentication using google spreadsheet

I am using oauth2 authentication java library to access google spreadsheet.

I am using the OAuth2 authentication code below:

credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token") .setServiceAccountScopes("https://www.googleapis.com/auth/drive", "https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds") .setServiceAccountPrivateKeyFromP12File(new File("xxxxx-privatekey.p12")).build(); 

After obtaining the "credentials" using the code below to read the spreadsheet:

 SpreadsheetService service = new SpreadsheetService( "MySpreadsheetIntegration"); service.setOAuth2Credentials(credential); URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full"); SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class); System.out.println(feed.getTotalResults()); 

Executing the above code returns me a final result of 0.

If I use:

 service.setUserCredentials("email", "password"); 

instead of oauth2 authentication, it returns me the correct results. Not sure what is wrong with OAuth2 authentication. Also, when I print the “access token” from the “credentials” object, it prints a valid access token.

+4
source share
1 answer

I use:

 spreadsheetService = new SpreadsheetService("cellmaster.com.au-v0.2"); spreadsheetService.setHeader("Authorization", "Bearer " + accessToken); 

but not:

 spreadsheetService = new SpreadsheetService("cellmaster.com.au-v0.2"); spreadsheetService.setOAuth2Credentials(credential); 

I also had to add code for the update token. When the access token will expire soon. But the update token works as you expected.

+2
source

Source: https://habr.com/ru/post/970750/


All Articles