Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

java - Issue with OAuth2 authentication with google spreadsheet

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...