获取OAuth2对用户的电子邮件地址进行身份验证

时间:2016-07-22 00:43:03

标签: java google-oauth google-api-java-client

我正在努力想出一个使用Google的OAuth2登录系统的工作示例,然后询问用户的信息(如姓名和/或电子邮件)。到目前为止,这是我设法:

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"
}

但我正在寻找用户的电子邮件(他/她用来登录系统的电子邮件)。如何获取用户的电子邮件地址?

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

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

1 个答案:

答案 0 :(得分:0)

我找到了它,它必须是:

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也有电子邮件地址。