Package cloud.google.com/go/auth/credentials (v0.16.0)

Package credentials provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. It supports the Web server flow, client-side credentials, service accounts, Google Compute Engine service accounts, Google App Engine service accounts and workload identity federation from non-Google cloud platforms.

A brief overview of the package follows. For more information, please read https://developers.google.com/accounts/docs/OAuth2 and https://developers.google.com/accounts/docs/application-default-credentials. For more information on using workload identity federation, refer to https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation.

Credentials

The cloud.google.com/go/auth.Credentials type represents Google credentials, including Application Default Credentials.

Use DetectDefault to obtain Application Default Credentials.

Application Default Credentials support workload identity federation to access Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload identity federation is recommended for non-Google Cloud environments as it avoids the need to download, manage, and store service account private keys locally.

Workforce Identity Federation

For more information on this feature see cloud.google.com/go/auth/credentials/externalaccount.

Constants

GoogleMTLSTokenURL

const (

	// GoogleMTLSTokenURL is Google's default OAuth2.0 mTLS endpoint.
	GoogleMTLSTokenURL = "https://oauth2.mtls.googleapis.com/token"
)

Functions

func DetectDefault

func DetectDefault(opts *DetectOptions) (*auth.Credentials, error)

DetectDefault searches for "Application Default Credentials" and returns a credential based on the [DetectOptions] provided.

It looks for credentials in the following places, preferring the first location found:

  • A JSON file whose path is specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable. For workload identity federation, refer to https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation on how to generate the JSON configuration file for on-prem/non-Google cloud platforms.
  • A JSON file in a location known to the gcloud command-line tool. On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. On other systems, $HOME/.config/gcloud/application_default_credentials.json.
  • On Google Compute Engine, Google App Engine standard second generation runtimes, and Google App Engine flexible environment, it fetches credentials from the metadata server.

Examples

package main

import (
	"log"

	"cloud.google.com/go/auth/credentials"
	"cloud.google.com/go/auth/httptransport"
)

func main() {
	creds, err := credentials.DetectDefault(&credentials.DetectOptions{
		Scopes: []string{"https://www.googleapis.com/auth/devstorage.full_control"},
	})
	if err != nil {
		log.Fatal(err)
	}
	client, err := httptransport.NewClient(&httptransport.Options{
		Credentials: creds,
	})
	if err != nil {
		log.Fatal(err)
	}
	client.Get("...")
}
withFilepath
package main

import (
	"log"

	"cloud.google.com/go/auth/credentials"
	"cloud.google.com/go/auth/httptransport"
)

func main() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	// Navigate to your project, then see the "Credentials" page
	// under "APIs & Auth".
	// To create a service account client, click "Create new Client ID",
	// select "Service Account", and click "Create Client ID". A JSON
	// key file will then be downloaded to your computer.
	filepath := "/path/to/your-project-key.json"
	creds, err := credentials.DetectDefault(&credentials.DetectOptions{
		Scopes:          []string{"https://www.googleapis.com/auth/bigquery"},
		CredentialsFile: filepath,
	})
	if err != nil {
		log.Fatal(err)
	}
	client, err := httptransport.NewClient(&httptransport.Options{
		Credentials: creds,
	})
	if err != nil {
		log.Fatal(err)
	}
	client.Get("...")
}
withJSON
package main

import (
	"log"
	"os"

	"cloud.google.com/go/auth/credentials"
	"cloud.google.com/go/auth/httptransport"
)

func main() {
	data, err := os.ReadFile("/path/to/key-file.json")
	if err != nil {
		log.Fatal(err)
	}
	creds, err := credentials.DetectDefault(&credentials.DetectOptions{
		Scopes:          []string{"https://www.googleapis.com/auth/bigquery"},
		CredentialsJSON: data,
	})
	if err != nil {
		log.Fatal(err)
	}
	client, err := httptransport.NewClient(&httptransport.Options{
		Credentials: creds,
	})
	if err != nil {
		log.Fatal(err)
	}
	client.Get("...")
}

func OnGCE

func OnGCE() bool

OnGCE reports whether this process is running in Google Cloud.

DetectOptions

type DetectOptions struct {
	// Scopes that credentials tokens should have. Example:
	// https://www.googleapis.com/auth/cloud-platform. Required if Audience is
	// not provided.
	Scopes []string
	// TokenBindingType specifies the type of binding used when requesting a
	// token whether to request a hard-bound token using mTLS or an instance
	// identity bound token using ALTS. Optional.
	TokenBindingType TokenBindingType
	// Audience that credentials tokens should have. Only applicable for 2LO
	// flows with service accounts. If specified, scopes should not be provided.
	Audience string
	// Subject is the user email used for [domain wide delegation](https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority).
	// Optional.
	Subject string
	// EarlyTokenRefresh configures how early before a token expires that it
	// should be refreshed. Once the token’s time until expiration has entered
	// this refresh window the token is considered valid but stale. If unset,
	// the default value is 3 minutes and 45 seconds. Optional.
	EarlyTokenRefresh time.Duration
	// DisableAsyncRefresh configures a synchronous workflow that refreshes
	// stale tokens while blocking. The default is false. Optional.
	DisableAsyncRefresh bool
	// AuthHandlerOptions configures an authorization handler and other options
	// for 3LO flows. It is required, and only used, for client credential
	// flows.
	AuthHandlerOptions *auth.AuthorizationHandlerOptions
	// TokenURL allows to set the token endpoint for user credential flows. If
	// unset the default value is: https://oauth2.googleapis.com/token.
	// Optional.
	TokenURL string
	// STSAudience is the audience sent to when retrieving an STS token.
	// Currently this only used for GDCH auth flow, for which it is required.
	STSAudience string
	// CredentialsFile overrides detection logic and sources a credential file
	// from the provided filepath. If provided, CredentialsJSON must not be.
	// Optional.
	//
	// Important: If you accept a credential configuration (credential
	// JSON/File/Stream) from an external source for authentication to Google
	// Cloud Platform, you must validate it before providing it to any Google
	// API or library. Providing an unvalidated credential configuration to
	// Google APIs can compromise the security of your systems and data. For
	// more information, refer to [Validate credential configurations from
	// external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).
	CredentialsFile string
	// CredentialsJSON overrides detection logic and uses the JSON bytes as the
	// source for the credential. If provided, CredentialsFile must not be.
	// Optional.
	//
	// Important: If you accept a credential configuration (credential
	// JSON/File/Stream) from an external source for authentication to Google
	// Cloud Platform, you must validate it before providing it to any Google
	// API or library. Providing an unvalidated credential configuration to
	// Google APIs can compromise the security of your systems and data. For
	// more information, refer to [Validate credential configurations from
	// external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).
	CredentialsJSON []byte
	// UseSelfSignedJWT directs service account based credentials to create a
	// self-signed JWT with the private key found in the file, skipping any
	// network requests that would normally be made. Optional.
	UseSelfSignedJWT bool
	// Client configures the underlying client used to make network requests
	// when fetching tokens. Optional.
	Client *http.Client
	// UniverseDomain is the default service domain for a given Cloud universe.
	// The default value is "googleapis.com". This option is ignored for
	// authentication flows that do not support universe domain. Optional.
	UniverseDomain string
	// Logger is used for debug logging. If provided, logging will be enabled
	// at the loggers configured level. By default logging is disabled unless
	// enabled by setting GOOGLE_SDK_GO_LOGGING_LEVEL in which case a default
	// logger will be used. Optional.
	Logger *slog.Logger
}

DetectOptions provides configuration for [DetectDefault].

TokenBindingType

type TokenBindingType int

TokenBindingType specifies the type of binding used when requesting a token whether to request a hard-bound token using mTLS or an instance identity bound token using ALTS.

NoBinding, MTLSHardBinding, ALTSHardBinding

const (
	// NoBinding specifies that requested tokens are not required to have a
	// binding. This is the default option.
	NoBinding TokenBindingType = iota
	// MTLSHardBinding specifies that a hard-bound token should be requested
	// using an mTLS with S2A channel.
	MTLSHardBinding
	// ALTSHardBinding specifies that an instance identity bound token should
	// be requested using an ALTS channel.
	ALTSHardBinding
)