2016-07-22 14 views
1

Ich versuche ein funktionierendes Beispiel zu finden, um mich mit OAuth2 von Google in das System einzuloggen und dann nach Benutzerinformationen (wie Name und/oder E-Mail) zu fragen. Das ist soweit ich so weit gehen geschaffen:Ermitteln der E-Mail-Adresse des Benutzers durch OAuth2 authentifiziert

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()); 

Und funktioniert perfekt, außer der Tatsache, dass die zurücken Benutzer Informationen per E-Mail nicht daran haben! Die gedruckte Informationen sind:

{ 
    "family_name" : "...", 
    "gender" : "...", 
    "given_name" : "...", 
    "id" : "...", 
    "link" : "https://plus.google.com/+...", 
    "locale" : "en-GB", 
    "name" : "... ...", 
    "picture" : "https://.../photo.jpg" 
} 

Aber ich bin auf der Suche für die E-Mail des Benutzers (die, die er/sie verwendet, um in das System einzuloggen). Wie kann ich die E-Mail-Adresse des Benutzers erhalten?

BTW, wenn Sie sich fragen; PeopleScopes.USERINFO_PROFILE ist:

https://www.googleapis.com/auth/userinfo.profile 

Antwort

0

ich es gefunden, muss es sein:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    GoogleNetHttpTransport.newTrustedTransport(), 
    JacksonFactory.getDefaultInstance(), 
    clientSecrets, 
    Arrays.asList(
     PeopleScopes.USERINFO_PROFILE, 
     PeopleScopes.USERINFO_EMAIL 
    ) 
) 

Und PeopleScopes.USERINFO_EMAIL steht für:

https://www.googleapis.com/auth/userinfo.email 

Nun ist die userinfo hat auch bekam E-Mail-Adresse.

Verwandte Themen