title: Authenticating Google API with a service account with Java API
body: <p>I am attempting to use oauth API to authenticate a google service account through the Java API. I am hoping to use it to access Google Bigquery. I get an "invalid grant" returned from my API requests.</p>
  
  <p>Here is the code, which is a copy of a basic authentication example (which wasn't for Bigquery.. but another Google API):</p>
  
  <pre><code>  /** Global instance of the HTTP transport. */
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
  
    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  
    private static Bigquery bigquery;  
  
  public ServiceAccountExample() {
  
        try {
            try {
  
              GoogleCredential credential = new  GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                  .setJsonFactory(JSON_FACTORY)
                  .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                  .setServiceAccountScopes(BigqueryScopes.BIGQUERY)
                  .setServiceAccountPrivateKeyFromP12File(new File("GoogleBigQuery-privatekey.p12"))
                  //.setRefreshListeners(refreshListeners)
                  //.setServiceAccountUser("email.com")
                  .build();
  
  
              credential.refreshToken();
  
              bigquery = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                          //.setApplicationName("GoogleBigQuery/1.0")
                          .build();
  
              listDatasets(bigquery, "publicdata");
  
              return;
            } catch (IOException e) {
              System.err.println(e.getMessage());
            }
          } catch (Throwable t) {
            t.printStackTrace();
          }
  
  }
  </code></pre>
  
  <p>SERVICE_ACCOUNT_EMAIL is the email address of the form: XXXXXXX@developer.gserviceaccount.com</p>
  
  <p>If I remove the credential.refreshToken() line, it fails in the listsDatasets on the first call to Bigquery... Otherwise it fails on credential.refreshToken().. with the same error.</p>
  
  <p>Does BigQuery not accept Service Account authentication?</p>
  
  <p>I believe I have done everything correctly through the API Console. I have:</p>
  
  <ul>
  <li>Turned access to the Big Query API on.</li>
  <li>Created a service account under the "API Access" tab.</li>
  <li>Downloaded my private key (which is referenced from the code above).</li>
  <li>Given my service account user "can edit" access under the "Teams" tab.</li>
  <li>Enabled Billing.</li>
  </ul>
  
  <p>Have I missed anything? Is there anything else I need to do?</p>
  
  <p>Thanks..</p>