繁体   English   中英

Java:Google日历身份验证

[英]Java: Google Calendar Authentication

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

您可以通过使用AuthorizationCodeInstalledApp来获取Credential 以下示例代码是从Google+命令行示例复制而来的。 它使用与您相似的身份验证流程,但它会创建一个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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM