title: Java: Google Calendar Authentication
body: <p>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.</p>
  
  <p>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. </p>
  
  <p>Would appreciate guidance on how to achieve such a feature, and what libraries I should use, or any particular methods to achieve this. </p>
  
  <p>This is the method which generates a URL for the user to navigate to, and returns this URL:</p>
  
  <pre><code>public static String generateNewTokenStep1()  {
  
  
          HttpTransport httpTransport = new NetHttpTransport();
          JsonFactory jsonFactory = new JacksonFactory();
  
          // Create the authorization code flow manager
          Set&lt;String&gt; 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();
  
      }
  </code></pre>
  
  <p>This is the method which takes in the success code generated by Google.</p>
  
  <pre><code>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();
      }
  </code></pre>