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

标签 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

最佳答案

我找到了,它一定是:

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

关于java - 获取通过 OAuth2 验证的用户电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38516484/

相关文章:

java - Google Gmail API - 无法加载用户电子邮件签名

java - <load-on-startup> 对于 Java Web 应用程序部署描述符中的 servlet 是可选的吗?

java - Android Location Distance为空

java - 运行 Java ScreenGrabber 示例

google-cloud-platform - 从运行在 Google Cloud VM 实例上的应用程序访问 Google Secrets - 将 Cloud API 分配给 VM

android - 如何在共享首选项中存储来自 OAuth2 的凭据

go - Golang OAuth客户端和刷新 token

coldfusion - Google Java API 与 ColdFusion CFHTTP 冲突?

java - (JAVA) Google API 分析 - 无法使用 "access token"获取新的 "refresh token"

java - 如果在静态初始化程序 block 中创建线程,程序将挂起