gpt4 book ai didi

java - 如何在 Java 中获取 GoogleAuthorizationCodeTokenRequest 的授权码?

转载 作者:搜寻专家 更新时间:2023-11-01 03:54:20 26 4
gpt4 key购买 nike

        HttpTransport netTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleTokenResponse token;
try {
token = new GoogleAuthorizationCodeTokenRequest(
netTransport,
jsonFactory,
CLIENT_ID,
CLIENT_SECRET,
CODE,
REDIRECT).execute();

GoogleCredential cd = new GoogleCredential().setAccessToken(token
.getAccessToken());

Plus plus = Plus
.builder(new NetHttpTransport(), new JacksonFactory())
.setApplicationName(APP_NAME)
.setHttpRequestInitializer(cd).build();

Person profile = plus.people().get("me").execute();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

大家好,我正在尝试在我的 Google App Engine 应用程序中从 Google+ 获取一些用户信息,但我对放置什么/如何获取 GoogleAuthorizationCodeTokenRequest 的 CODE 参数感到困惑。任何帮助是极大的赞赏。谢谢。

最佳答案

我会尝试改进 Remy Ticona 的回答。基本的 oAuth 授权流程是:

  1. 请求用户访问。您的应用程序应将用户重定向到授权网址。在该页面上,谷歌要求用户访问。
  2. 在用户授予访问权限后,他将被重定向到 REDIRECT_URL。在那里你可以选择最适合你的选项:
    1. 您的应用具有内置网络浏览器。使用 urn:ietf:wg:oauth:2.0:oob:auto 作为 url。当用户授予访问权限时,您的应用应从网页标题中读取访问代码。
    2. 您的应用作为网络服务器。使用您的网络应用程序的网址。访问代码将是一个查询参数,您可以处理它
    3. 您的应用不具备上述功能。使用 urn:ietf:wg:oauth:2.0:oob 作为 REDIRECT_URL。当用户授予访问权限时,他将被重定向到包含访问代码的页面,并请求将其复制并粘贴到您的应用中。

您可以在这里找到详细信息:https://developers.google.com/identity/protocols/OAuth2InstalledApp?hl=RU#choosingredirecturi

小例子:

GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow
.Builder(httpTransport, jsonFactory, clientId, clientSecret, scopes)
.setCredentialDataStore(new MemoryDataStoreFactory().getDataStore("tokens"))
.build();
String userId = "user-id";
Credential credential = authorizationCodeFlow.loadCredential(userId);
if (credential == null) {
GoogleAuthorizationCodeRequestUrl authorizationUrl = authorizationCodeFlow.newAuthorizationUrl();
authorizationUrl.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI);
LOGGER.error("Please, authorize application. Visit {}", authorizationUrl);
Scanner s = new Scanner(System.in);
String code = s.nextLine();
GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(code);
tokenRequest.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI);
GoogleTokenResponse tokenResponse = tokenRequest.execute();
credential = authorizationCodeFlow.createAndStoreCredential(tokenResponse, userId);
}

关于java - 如何在 Java 中获取 GoogleAuthorizationCodeTokenRequest 的授权码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13450460/

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