gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:24:30 26 4
gpt4 key购买 nike

我正在尝试提出一个使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com