Java:Google日历身份验证

时间:2014-10-28 19:29:14

标签: java calendar google-calendar-api

我正在寻找一种验证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();

    }

这是接收Google生成的成功代码的方法。

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();
    }

1 个答案:

答案 0 :(得分:0)

您可以使用AuthorizationCodeInstalledApp来获取Credential。以下示例代码是从Google+ command line sample复制的。它使用类似的auth流程,除了它创建一个监听和接收代码的LocalServerReceiver,因此用户不必执行任何手动步骤。

// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

// Load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory,
    new InputStreamReader(PlusSample.class.getResourceAsStream("/client_secrets.json")));

// Set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport, jsonFactory, clientSecrets,
    Collections.singleton(PlusScopes.PLUS_ME)).setDataStoreFactory(dataStoreFactory)
    .build();

// Authorize
Credential credential =
    new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");