Package cloud.google.com/go/auth (v0.17.0) Stay organized with collections Save and categorize content based on your preferences.
Package auth provides utilities for managing Google Cloud credentials,including functionality for creating, caching, and refreshing OAuth2 tokens.It offers customizable options for different OAuth2 flows, such as 2-legged(2LO) and 3-legged (3LO) OAuth, along with support for PKCE and automatictoken management.
AuthorizationHandler
AuthorizationHandler is a 3-legged-OAuth helper that prompts the user forOAuth consent at the specified auth code URL and returns an auth code andstate upon approval.
AuthorizationHandlerOptions
typeAuthorizationHandlerOptionsstruct{// AuthorizationHandler specifies the handler used to for the authorization// part of the flow.HandlerAuthorizationHandler// State is used verify that the "state" is identical in the request and// response before exchanging the auth code for OAuth2 token.Statestring// PKCEOpts allows setting configurations for PKCE. Optional.PKCEOpts*PKCEOptions}AuthorizationHandlerOptions provides a set of options to specify for doing a3-legged OAuth2 flow with a custom [AuthorizationHandler].
CachedTokenProviderOptions
typeCachedTokenProviderOptionsstruct{// DisableAutoRefresh makes the TokenProvider always return the same token,// even if it is expired. The default is false. Optional.DisableAutoRefreshbool// ExpireEarly configures the amount of time before a token expires, that it// should be refreshed. If unset, the default value is 3 minutes and 45// seconds. Optional.ExpireEarlytime.Duration// DisableAsyncRefresh configures a synchronous workflow that refreshes// tokens in a blocking manner. The default is false. Optional.DisableAsyncRefreshbool}CachedTokenProviderOptions provides options for configuring a cached[TokenProvider].
Credentials
typeCredentialsstruct{TokenProvider// contains filtered or unexported fields}Credentials holds Google credentials, includingApplication Default Credentials.
func NewCredentials
funcNewCredentials(opts*CredentialsOptions)*CredentialsNewCredentials returns new [Credentials] from the provided options.
func (*Credentials) JSON
func(c*Credentials)JSON()[]byteJSON returns the bytes associated with the the file used to sourcecredentials if one was used.
func (*Credentials) ProjectID
func(c*Credentials)ProjectID(ctxcontext.Context)(string,error)ProjectID returns the associated project ID from the underlying file orenvironment.
func (*Credentials) QuotaProjectID
func(c*Credentials)QuotaProjectID(ctxcontext.Context)(string,error)QuotaProjectID returns the associated quota project ID from the underlyingfile or environment.
func (*Credentials) UniverseDomain
func(c*Credentials)UniverseDomain(ctxcontext.Context)(string,error)UniverseDomain returns the default service domain for a given Cloud universe.The default value is "googleapis.com".
CredentialsOptions
typeCredentialsOptionsstruct{// TokenProvider is a means of sourcing a token for the credentials. Required.TokenProviderTokenProvider// JSON is the raw contents of the credentials file if sourced from a file.JSON[]byte// ProjectIDProvider resolves the project ID associated with the// credentials.ProjectIDProviderCredentialsPropertyProvider// QuotaProjectIDProvider resolves the quota project ID associated with the// credentials.QuotaProjectIDProviderCredentialsPropertyProvider// UniverseDomainProvider resolves the universe domain with the credentials.UniverseDomainProviderCredentialsPropertyProvider}CredentialsOptions are used to configure [Credentials].
CredentialsPropertyFunc
CredentialsPropertyFunc is a type adapter to allow the use of ordinaryfunctions as a [CredentialsPropertyProvider].
func (CredentialsPropertyFunc) GetProperty
func(pCredentialsPropertyFunc)GetProperty(ctxcontext.Context)(string,error)GetProperty loads the properly value provided the given context.
CredentialsPropertyProvider
CredentialsPropertyProvider provides an implementation to fetch a propertyvalue for [Credentials].
Error
typeErrorstruct{// Response is the HTTP response associated with error. The body will always// be already closed and consumed.Response*http.Response// Body is the HTTP response body.Body[]byte// Err is the underlying wrapped error.Errerror// contains filtered or unexported fields}Error is a error associated with retrieving a [Token]. It can hold usefuladditional details for debugging.
func (*Error) Error
func (*Error) Temporary
Temporary returns true if the error is considered temporary and may be ableto be retried.
func (*Error) Unwrap
Options2LO
typeOptions2LOstruct{// Email is the OAuth2 client ID. This value is set as the "iss" in the// JWT.Emailstring// PrivateKey contains the contents of an RSA private key or the// contents of a PEM file that contains a private key. It is used to sign// the JWT created.PrivateKey[]byte// TokenURL is th URL the JWT is sent to. Required.TokenURLstring// PrivateKeyID is the ID of the key used to sign the JWT. It is used as the// "kid" in the JWT header. Optional.PrivateKeyIDstring// Subject is the used for to impersonate a user. It is used as the "sub" in// the JWT.m Optional.Subjectstring// Scopes specifies requested permissions for the token. Optional.Scopes[]string// Expires specifies the lifetime of the token. Optional.Expirestime.Duration// Audience specifies the "aud" in the JWT. Optional.Audiencestring// PrivateClaims allows specifying any custom claims for the JWT. Optional.PrivateClaimsmap[string]interface{}// UniverseDomain is the default service domain for a given Cloud universe.UniverseDomainstring// Client is the client to be used to make the underlying token requests.// Optional.Client*http.Client// UseIDToken requests that the token returned be an ID token if one is// returned from the server. Optional.UseIDTokenbool// 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}Options2LO is the configuration settings for doing a 2-legged JWT OAuth2 flow.
Options3LO
typeOptions3LOstruct{// ClientID is the application's ID.ClientIDstring// ClientSecret is the application's secret. Not required if AuthHandlerOpts// is set.ClientSecretstring// AuthURL is the URL for authenticating.AuthURLstring// TokenURL is the URL for retrieving a token.TokenURLstring// AuthStyle is used to describe how to client info in the token request.AuthStyleStyle// RefreshToken is the token used to refresh the credential. Not required// if AuthHandlerOpts is set.RefreshTokenstring// RedirectURL is the URL to redirect users to. Optional.RedirectURLstring// Scopes specifies requested permissions for the Token. Optional.Scopes[]string// URLParams are the set of values to apply to the token exchange. Optional.URLParamsurl.Values// Client is the client to be used to make the underlying token requests.// Optional.Client*http.Client// EarlyTokenExpiry is the time before the token expires that it should be// refreshed. If not set the default value is 3 minutes and 45 seconds.// Optional.EarlyTokenExpirytime.Duration// AuthHandlerOpts provides a set of options for doing a// 3-legged OAuth2 flow with a custom [AuthorizationHandler]. Optional.AuthHandlerOpts*AuthorizationHandlerOptions// 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}Options3LO are the options for doing a 3-legged OAuth2 flow.
PKCEOptions
typePKCEOptionsstruct{// Challenge is the un-padded, base64-url-encoded string of the encrypted code verifier.Challengestring// The un-padded, base64-url-encoded string of the encrypted code verifier.// ChallengeMethod is the encryption method (ex. S256).ChallengeMethodstring// Verifier is the original, non-encrypted secret.Verifierstring// The original, non-encrypted secret.}PKCEOptions holds parameters to support PKCE.
Style
typeStyleintStyle describes how the token endpoint wants to receive the ClientID andClientSecret.
StyleUnknown, StyleInParams, StyleInHeader
const(// StyleUnknown means the value has not been initiated. Sending this in// a request will cause the token exchange to fail.StyleUnknownStyle=iota// StyleInParams sends client info in the body of a POST request.StyleInParams// StyleInHeader sends client info using Basic Authorization header.StyleInHeader)Token
typeTokenstruct{// Value is the token used to authorize requests. It is usually an access// token but may be other types of tokens such as ID tokens in some flows.Valuestring// Type is the type of token Value is. If uninitialized, it should be// assumed to be a "Bearer" token.Typestring// Expiry is the time the token is set to expire.Expirytime.Time// Metadata may include, but is not limited to, the body of the token// response returned by the server.Metadatamap[string]interface{}// TODO(codyoss): maybe make a method to flatten metadata to avoid []string for url.Values}Token holds the credential token used to authorized requests. All fields areconsidered read-only.
func (*Token) IsValid
IsValid reports that a [Token] is non-nil, has a [Token.Value], and has notexpired. A token is considered expired if [Token.Expiry] has passed or willpass in the next 225 seconds.
func (*Token) MetadataString
MetadataString is a convenience method for accessing string values in thetoken's metadata. Returns an empty string if the metadata is nil or the valuefor the given key cannot be cast to a string.
TokenProvider
typeTokenProviderinterface{// Token returns a Token or an error.// The Token returned must be safe to use// concurrently.// The returned Token must not be modified.// The context provided must be sent along to any requests that are made in// the implementing code.Token(context.Context)(*Token,error)}TokenProvider specifies an interface for anything that can return a token.
func New2LOTokenProvider
funcNew2LOTokenProvider(opts*Options2LO)(TokenProvider,error)New2LOTokenProvider returns a [TokenProvider] from the provided options.
Example
packagemainimport("log""cloud.google.com/go/auth""cloud.google.com/go/auth/httptransport")funcmain(){// Your credentials should be obtained from the Google// Developer Console (https://console.developers.google.com).opts:=&auth.Options2LO{Email:"xxx@developer.gserviceaccount.com",// The contents of your RSA private key or your PEM file// that contains a private key.// If you have a p12 file instead, you// can use `openssl` to export the private key into a pem file.//// $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes//// The field only supports PEM containers with no passphrase.// The openssl command will convert p12 keys to passphrase-less PEM containers.PrivateKey:[]byte("-----BEGIN RSA PRIVATE KEY-----..."),Scopes:[]string{"https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/blogger",},TokenURL:"https://oauth2.googleapis.com/token",// If you would like to impersonate a user, you can// create a transport with a subject. The following GET// request will be made on the behalf of user@example.com.// Optional.Subject:"user@example.com",}tp,err:=auth.New2LOTokenProvider(opts)iferr!=nil{log.Fatal(err)}client,err:=httptransport.NewClient(&httptransport.Options{Credentials:auth.NewCredentials(&auth.CredentialsOptions{TokenProvider:tp,}),})iferr!=nil{log.Fatal(err)}client.Get("...")_=tp}func New3LOTokenProvider
funcNew3LOTokenProvider(opts*Options3LO)(TokenProvider,error)New3LOTokenProvider returns a [TokenProvider] based on the 3-legged OAuth2configuration. The TokenProvider is caches and auto-refreshes tokens bydefault.
func NewCachedTokenProvider
funcNewCachedTokenProvider(tpTokenProvider,opts*CachedTokenProviderOptions)TokenProviderNewCachedTokenProvider wraps a [TokenProvider] to cache the tokens returnedby the underlying provider. By default it will refresh tokens asynchronouslya few minutes before they expire.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-10-30 UTC.