Authenticate with client libraries

This page describes how you can use client libraries to access Google APIs.

Client libraries make it easier to access Google Cloud APIs using a supported language. You can use Google Cloud APIs directly by making raw requests to the server, but client libraries provide simplifications that significantly reduce the amount of code you need to write. This is especially true for authentication, because the client libraries support Application Default Credentials (ADC).

If you accept credential configurations (JSON, files, or streams) from an external source (for example, a customer), review the security requirements when using credential configurations from an external source.

Use Application Default Credentials with client libraries

To use Application Default Credentials to authenticate your application, you must first set up ADC for the environment where your application is running. When you use the client library to create a client, the client library automatically checks for and uses the credentials you have provided to ADC to authenticate to the APIs your code uses. Your application does not need to explicitly authenticate or manage tokens; these requirements are managed automatically by the authentication libraries.

For a local development environment, you can set up ADC with your user credentials or with service account impersonation by using the gcloud CLI. For production environments, you set up ADC by attaching a service account.

Example client creation

The following code samples create a client for the Cloud Storage service. Your code is likely to need different clients; these samples are meant only to show how you can create a client and use it without any code to explicitly authenticate.

Before you can run the following samples, you must complete the following steps:

Go

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// authenticateImplicitWithAdc uses Application Default Credentials
// to automatically find credentials and authenticate.
func authenticateImplicitWithAdc(w io.Writer, projectId string) error {
	// projectId := "your_project_id"

	ctx := context.Background()

	// NOTE: Replace the client created below with the client required for your application.
	// Note that the credentials are not specified when constructing the client.
	// The client library finds your credentials using ADC.
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	it := client.Buckets(ctx, projectId)
	for {
		bucketAttrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err