【发布时间】:2014-10-28 19:29:14
【问题描述】:
我正在寻找一种验证 Google 日历的方法。现在,我们编写应用程序的方式包括生成一个身份验证 URL,让用户导航到该 URL,并将“成功代码”复制并粘贴到程序中,然后输入它,以便处理身份验证令牌。
我正在寻找一种自动化该过程的方法:让我们的应用直接读取从用户浏览器窗口生成的成功代码。这消除了用户手动复制和粘贴代码的需要。
希望获得有关如何实现此类功能、我应该使用哪些库或任何特定方法来实现此功能的指导。
这个方法会生成一个 URL 供用户导航,并返回这个 URL:
public static String generateNewTokenStep1() {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
// Create the authorization code flow manager
Set<String> scope = Collections.singleton(CalendarScopes.CALENDAR);
String clientId = "_______";
String clientSecret = "__________";
AuthorizationCodeFlow.Builder codeFlowBuilder = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, clientId, clientSecret, scope);
codeFlow = codeFlowBuilder.build();
String userId = USER_ID;
// "redirect" to the authentication url
redirectUri = "urn:ietf:wg:oauth:2.0:oob";
AuthorizationCodeRequestUrl authorizationUrl = codeFlow
.newAuthorizationUrl();
authorizationUrl.setRedirectUri(redirectUri);
return authorizationUrl.toString();
}
这是接收谷歌生成的成功码的方法。
public static String generateNewTokenStep2(String userInput) {
String code = userInput;
AuthorizationCodeTokenRequest tokenRequest = codeFlow
.newTokenRequest(code);
tokenRequest.setRedirectUri(redirectUri);
TokenResponse tokenResponse = null;
try {
tokenResponse = tokenRequest.execute();
} catch (IOException tokenRequestFailed) {
System.err.println("Token request failed");
}
System.out.println(tokenResponse.getAccessToken());
addToDb(tokenResponse.getAccessToken());
return tokenResponse.getAccessToken();
}
【问题讨论】:
-
您可以选择使用redirect_uri 来获取对所需端口或Web 服务器的响应吗? developers.google.com/accounts/docs/…
标签: java calendar google-calendar-api