获取通过 OAuth2 验证的用户电子邮件地址

Getting user's email address authenticated by OAuth2

我正在尝试提出一个工作示例,使用 Google 的 OAuth2 登录系统,然后询问用户信息(如姓名 and/or 电子邮件)。这是我到目前为止所能做到的:

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

除了返回的用户信息中没有我的电子邮件之外,它工作得很好!打印的信息是:

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

但我正在查找用户的电子邮件(he/she 用于登录系统的电子邮件)。如何获取用户的电子邮件地址?

顺便说一句,如果你想知道; PeopleScopes.USERINFO_PROFILE 是:

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

我找到了,必须是:

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

PeopleScopes.USERINFO_EMAIL代表:

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

现在 userinfo 也有电子邮件地址了。