Issue with OAuth2 authentication with google spreadsheet

…衆ロ難τιáo~ 提交于 2019-12-28 06:50:08

问题


I am using java library for oauth2 authentication for accessing google spreadsheet.

I am using below code for OAuth2 authentication:

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 getting "credential", using below code to read 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 above code give me back total result 0.

If I use:

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

in place of oauth2 authentication, it gives me back correct results. Not sure what is wrong with the OAuth2 authentication. Also when I print "access token" from "credential" object it prints a valid access token.


回答1:


I use:

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

rather than:

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

also I had to add code for the refresh token. As the access token soon expires. But the refresh token works as you would expect.



来源:https://stackoverflow.com/questions/15084133/issue-with-oauth2-authentication-with-google-spreadsheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!