Search code examples
google-apigoogle-oauthservice-accountsgoogle-developers-console

How to generate "client_secret.json" for Google API with offline access?


I am trying to authenticate to Google API in a backend service using a service account. It will not have a UI at all.

I have generated private keys in JSON format from Google Developer Console, using a Service Account but there is no field named "client_secret" in it.

I found this example on GitHub, and its structure should be correctly parsed by GoogleClientSecrets class.

What are the steps to generate the correct client_secret.json as in the GitHub example?


Solution

  • I need to do this again after a long time, and I am documenting the steps as of May 2022.


    • Login to Google Cloud Console

    • Go to API Service -> Credentials

    • Click "+ Create Credentials", ans select Service Account

      • Fill in service account name, it will create a default account id
      • Click "Create and Continue"
      • In the role selection screen, I selected owner as this was my personal project. If your service will be accessed by external parties, consider giving only required permissions
      • Click Continue
      • I did not select any user/admin role on screen 3. Click Done.
    • You will be back on Credentials screen. Click the Service account Email you just created.

      • You should be on the Details tab. Click on the KEYS tab.
      • Click "Add Key" dropdown, and click "Create New Key".
      • Select JSON key type (default), and click create.
      • This should download a JSON file to you.

    You can then use the credential to access Google services. For example, in my case I access YouTube service with the following code ( clientSecretsStream is the InputStream of that credentials JSON file):

    public static YouTube initializeYouTube(InputStream clientSecretsStream, String appName) throws IOException {
        final HttpTransport httpTransport = new NetHttpTransport();
        final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
        GoogleCredential credential = GoogleCredential.fromStream(clientSecretsStream)
                .createScoped(Collections.singleton(YouTubeScopes.YOUTUBE_READONLY));
    
        return new YouTube.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName(appName)
                .build();
    }