简体   繁体   中英

Java: Google Calendar Authentication

I'm looking for a way to authenticate a Google Calendar. Right now, the way we have coded our app involves generating an authentication URL, and having the user navigate to that URL and to copy and paste a 'success code' into the program, and enter it, for an authentication token to be processed.

I'm looking for a way to automate that process: To make our app directly read the success code generated from the user's browser window. This removes the need for a manual copy and paste of the code, by the user.

Would appreciate guidance on how to achieve such a feature, and what libraries I should use, or any particular methods to achieve this.

This is the method which generates a URL for the user to navigate to, and returns this 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();

    }

This is the method which takes in the success code generated by 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();
    }

You can do this by using AuthorizationCodeInstalledApp to get the Credential . The following sample code is copied from the Google+ command line sample . It uses a similar auth flow to yours except it creates a LocalServerReceiver that listens for and receives the code so the user does not have to do any manual steps.

// 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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