Movatterモバイル変換


[0]ホーム

URL:


credentials

package
v0.18.0Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 15, 2025 License:Apache-2.0Imports:22Imported by:32

Details

Repository

github.com/googleapis/google-cloud-go

Links

Documentation

Overview

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

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

Credentials

Thecloud.google.com/go/auth.Credentials type represents Googlecredentials, including Application Default Credentials.

UseDetectDefault to obtain Application Default Credentials.

Application Default Credentials support workload identity federation toaccess Google Cloud resources from non-Google Cloud platforms including AmazonWeb Services (AWS), Microsoft Azure or any identity provider that supportsOpenID Connect (OIDC). Workload identity federation is recommended fornon-Google Cloud environments as it avoids the need to download, manage, andstore service account private keys locally.

Workforce Identity Federation

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

Index

Examples

Constants

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

Variables

This section is empty.

Functions

funcDetectDefault

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

DetectDefault searches for "Application Default Credentials" and returnsa credential based on theDetectOptions provided.

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

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

Important: If you accept a credential configuration (credentialJSON/File/Stream) from an external source for authentication to GoogleCloud Platform, you must validate it before providing it to any GoogleAPI or library. Providing an unvalidated credential configuration toGoogle APIs can compromise the security of your systems and data. Formore information, refer to [Validate credential configurations fromexternal sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).

Example
package mainimport ("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("...")}

Example (WithFilepath)
package mainimport ("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("...")}

Example (WithJSON)
package mainimport ("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("...")}

funcNewCredentialsFromFileadded inv0.18.0

func NewCredentialsFromFile(credTypeCredType, filenamestring, opts *DetectOptions) (*auth.Credentials,error)

NewCredentialsFromFile creates acloud.google.com/go/auth.Credentials fromthe provided file. The credType argument specifies the expected credentialtype. If the file content does not match the expected type, an error isreturned.

Important: If you accept a credential configuration (credentialJSON/File/Stream) from an external source for authentication to GoogleCloud Platform, you must validate it before providing it to any GoogleAPI or library. Providing an unvalidated credential configuration toGoogle APIs can compromise the security of your systems and data. Formore information, refer to [Validate credential configurations fromexternal sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).

funcNewCredentialsFromJSONadded inv0.18.0

func NewCredentialsFromJSON(credTypeCredType, b []byte, opts *DetectOptions) (*auth.Credentials,error)

NewCredentialsFromJSON creates acloud.google.com/go/auth.Credentials fromthe provided JSON bytes. The credType argument specifies the expectedcredential type. If the JSON does not match the expected type, an error isreturned.

Important: If you accept a credential configuration (credentialJSON/File/Stream) from an external source for authentication to GoogleCloud Platform, you must validate it before providing it to any GoogleAPI or library. Providing an unvalidated credential configuration toGoogle APIs can compromise the security of your systems and data. Formore information, refer to [Validate credential configurations fromexternal sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).

funcOnGCE

func OnGCE()bool

OnGCE reports whether this process is running in Google Cloud.

Types

typeCredTypeadded inv0.18.0

type CredTypestring

CredType specifies the type of JSON credentials being providedto a loading function such asNewCredentialsFromFile orNewCredentialsFromJSON.

const (// ServiceAccount represents a service account file type.ServiceAccountCredType = "service_account"// AuthorizedUser represents a user credentials file type.AuthorizedUserCredType = "authorized_user"// ExternalAccount represents an external account file type.//// IMPORTANT:// This credential type does not validate the credential configuration. A security// risk occurs when a credential configuration configured with malicious urls// is used.// You should validate credential configurations provided by untrusted sources.// See [Security requirements when using credential configurations from an external// source]https://cloud.google.com/docs/authentication/external/externally-sourced-credentials// for more details.ExternalAccountCredType = "external_account"// ImpersonatedServiceAccount represents an impersonated service account file type.//// IMPORTANT:// This credential type does not validate the credential configuration. A security// risk occurs when a credential configuration configured with malicious urls// is used.// You should validate credential configurations provided by untrusted sources.// See [Security requirements when using credential configurations from an external// source]https://cloud.google.com/docs/authentication/external/externally-sourced-credentials// for more details.ImpersonatedServiceAccountCredType = "impersonated_service_account"// GDCHServiceAccount represents a GDCH service account credentials.GDCHServiceAccountCredType = "gdch_service_account"// ExternalAccountAuthorizedUser represents an external account authorized user credentials.ExternalAccountAuthorizedUserCredType = "external_account_authorized_user")

typeDetectOptions

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.TokenBindingTypeTokenBindingType// Audience that credentials tokens should have. Only applicable for 2LO// flows with service accounts. If specified, scopes should not be provided.Audiencestring// Subject is the user email used for [domain wide delegation](https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority).// Optional.Subjectstring// 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.EarlyTokenRefreshtime.Duration// DisableAsyncRefresh configures a synchronous workflow that refreshes// stale tokens while blocking. The default is false. Optional.DisableAsyncRefreshbool// 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.TokenURLstring// STSAudience is the audience sent to when retrieving an STS token.// Currently this only used for GDCH auth flow, for which it is required.STSAudiencestring// CredentialsFile overrides detection logic and sources a credential file// from the provided filepath. If provided, CredentialsJSON must not be.// Optional.//// Deprecated: This field is deprecated because of a potential security risk.// It does not validate the credential configuration. The security risk occurs// when a credential configuration is accepted from a source that is not// under your control and used without validation on your side.//// If you know that you will be loading credential configurations of a// specific type, it is recommended to use a credential-type-specific// NewCredentialsFromFile method. This will ensure that an unexpected// credential type with potential for malicious intent is not loaded// unintentionally. You might still have to do validation for certain// credential types. Please follow the recommendation for that method. For// example, if you want to load only service accounts, you can use////creds, err := credentials.NewCredentialsFromFile(ctx, credentials.ServiceAccount, filename, opts)//// If you are loading your credential configuration from an untrusted source// and have not mitigated the risks (e.g. by validating the configuration// yourself), make these changes as soon as possible to prevent security// risks to your environment.//// Regardless of the method used, it is always your responsibility to// validate configurations received from external sources.//// For more details see://https://cloud.google.com/docs/authentication/external/externally-sourced-credentialsCredentialsFilestring// CredentialsJSON overrides detection logic and uses the JSON bytes as the// source for the credential. If provided, CredentialsFile must not be.// Optional.//// Deprecated: This field is deprecated because of a potential security risk.// It does not validate the credential configuration. The security risk occurs// when a credential configuration is accepted from a source that is not// under your control and used without validation on your side.//// If you know that you will be loading credential configurations of a// specific type, it is recommended to use a credential-type-specific// NewCredentialsFromJSON method. This will ensure that an unexpected// credential type with potential for malicious intent is not loaded// unintentionally. You might still have to do validation for certain// credential types. Please follow the recommendation for that method. For// example, if you want to load only service accounts, you can use////creds, err := credentials.NewCredentialsFromJSON(ctx, credentials.ServiceAccount, json, opts)//// If you are loading your credential configuration from an untrusted source// and have not mitigated the risks (e.g. by validating the configuration// yourself), make these changes as soon as possible to prevent security// risks to your environment.//// Regardless of the method used, it is always your responsibility to// validate configurations received from external sources.//// For more details see://https://cloud.google.com/docs/authentication/external/externally-sourced-credentialsCredentialsJSON []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.UseSelfSignedJWTbool// 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.UniverseDomainstring// 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 forDetectDefault.

typeTokenBindingTypeadded inv0.15.0

type TokenBindingTypeint

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

const (// NoBinding specifies that requested tokens are not required to have a// binding. This is the default option.NoBindingTokenBindingType =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)

Source Files

View all Source files

Directories

PathSynopsis
Package downscope implements the ability to downscope, or restrict, the Identity and Access Management permissions that a short-lived Token can use.
Package downscope implements the ability to downscope, or restrict, the Identity and Access Management permissions that a short-lived Token can use.
Package externalaccount provides support for creating workload identity federation and workforce identity federation token providers that can be used to access Google Cloud resources from external identity providers.
Package externalaccount provides support for creating workload identity federation and workforce identity federation token providers that can be used to access Google Cloud resources from external identity providers.
Package idtoken provides functionality for generating and validating ID tokens, with configurable options for audience, custom claims, and token formats.
Package idtoken provides functionality for generating and validating ID tokens, with configurable options for audience, custom claims, and token formats.
Package impersonate is used to impersonate Google Credentials.
Package impersonate is used to impersonate Google Credentials.
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp