Google Oauth for Backend Java Services

210 views Asked by At

I've a requirement to run a background service to pull Youtube Analytics for already linked channel on a daily basis using Youtube Analytics API

Since it'll be in the background, having a direct accesses with Google's Oauth services would be good like with grant_type client_credentials. But, the flow covered in all the samples Provided here, needs an entire flow where user has to Authorize from browser using Authorisation Flow

 GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
            .build();

    // Build the local server and bind it to port 8080
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

    // Authorize.
    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");

I've also tried working with an API key, but that is not supported by Analytics API. Anybody knows any way to generate and retrieve access_token based on a service account which allows backend job to consume Analytics API?

2

There are 2 answers

2
Linda Lawton - DaImTo On

There are three main types of credetilas that can be created on Google developer console.

  • Web credentials
  • Installed credentials
  • Service account Credentials

The Credentials file for each of those types is different as is the code. THe code you are using is for an installed application hence the AuthorizationCodeInstalledApp so unless you created installed credentials that code isn't going to work.

The code for service accounts should be something like this.

 HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(scopes);
2
Abhi On

Analytics API's access to any content cannot be done unless it's authorized by consent. Even with Server access, your server user won't have access to Analytics data of another channel directly. Possible option that I've gone with now:

  • During sign up process, get user to authorize your service account fo access.
  • Now your service account can access Channel data for the authorized channel.