I'm trying to to come up with a working example to log into the system using Google's OAuth2 and then ask for user's information (like name and/or email). This is as far as I managed to go so far:
InputStream in = Application.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
clientSecrets,
Arrays.asList(
PeopleScopes.USERINFO_PROFILE
)
)
.setAccessType("offline")
.build();
GoogleTokenResponse response = flow
.newTokenRequest(code)
.setRedirectUri("http://example.com/oauth2callback")
.execute();
Credential credential = flow.createAndStoreCredential(response, null);
Gmail service = new Gmail.Builder(GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
credential
)
.setApplicationName("My App")
.build();
Oauth2 oauth2 = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credential)
.setApplicationName("My App")
.build();
Userinfoplus userinfo = oauth2.userinfo().get().execute();
System.out.print(userinfo.toPrettyString());
And works perfectly except the fact that the returned user info does not have my email in it! The printed info are:
{
"family_name" : "...",
"gender" : "...",
"given_name" : "...",
"id" : "...",
"link" : "https://plus.google.com/+...",
"locale" : "en-GB",
"name" : "... ...",
"picture" : "https://.../photo.jpg"
}
But I'm looking for the user's email (the one that he/she used to log into the system). How can I get user's email address?
BTW, if you wonder; PeopleScopes.USERINFO_PROFILE
is:
https://www.googleapis.com/auth/userinfo.profile
I found it, it has to be:
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
clientSecrets,
Arrays.asList(
PeopleScopes.USERINFO_PROFILE,
PeopleScopes.USERINFO_EMAIL
)
)
And PeopleScopes.USERINFO_EMAIL
stands for:
https://www.googleapis.com/auth/userinfo.email
Now the userinfo
has got email address too.