1
我試圖想出一個工作示例,使用Google的OAuth2登錄系統,然後詢問用戶的信息(如姓名和/或電子郵件)。這是迄今爲止我設法走得如此之遠:獲取用戶的電子郵件地址通過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