Package cloud.google.com/go/auth (v0.3.0)

AuthorizationHandler

type AuthorizationHandler func(authCodeURL string) (code string, state string, err error)

AuthorizationHandler is a 3-legged-OAuth helper that prompts the user for OAuth consent at the specified auth code URL and returns an auth code and state upon approval.

AuthorizationHandlerOptions

type AuthorizationHandlerOptions struct {
	// AuthorizationHandler specifies the handler used to for the authorization
	// part of the flow.
	Handler AuthorizationHandler
	// State is used verify that the "state" is identical in the request and
	// response before exchanging the auth code for OAuth2 token.
	State string
	// PKCEOpts allows setting configurations for PKCE. Optional.
	PKCEOpts *PKCEOptions
}

AuthorizationHandlerOptions provides a set of options to specify for doing a 3-legged OAuth2 flow with a custom [AuthorizationHandler].

CachedTokenProviderOptions

type CachedTokenProviderOptions struct {
	// DisableAutoRefresh makes the TokenProvider always return the same token,
	// even if it is expired.
	DisableAutoRefresh bool
	// ExpireEarly configures the amount of time before a token expires, that it
	// should be refreshed. If unset, the default value is 10 seconds.
	ExpireEarly time.Duration
}

CachedTokenProviderOptions provided options for configuring a CachedTokenProvider.

Credentials

type Credentials struct {
	TokenProvider
	// contains filtered or unexported fields
}

Credentials holds Google credentials, including Application Default Credentials.

func NewCredentials

func NewCredentials(opts *CredentialsOptions) *Credentials

NewCredentials returns new [Credentials] from the provided options. Most users will want to build this object a function from the [cloud.google.com/go/auth/credentials] package.

func (*Credentials) JSON

func (c *Credentials) JSON() []byte

JSON returns the bytes associated with the the file used to source credentials if one was used.

func (*Credentials) ProjectID

func (c *Credentials) ProjectID(ctx context.Context) (string, error)

ProjectID returns the associated project ID from the underlying file or environment.

func (*Credentials) QuotaProjectID

func (c *Credentials) QuotaProjectID(ctx context.Context) (string, error)

QuotaProjectID returns the associated quota project ID from the underlying file or environment.

func (*Credentials) UniverseDomain

func (c *Credentials) UniverseDomain(ctx context.Context) (string, error)

UniverseDomain returns the default service domain for a given Cloud universe. The default value is "googleapis.com".

CredentialsOptions

type CredentialsOptions struct {
	// TokenProvider is a means of sourcing a token for the credentials. Required.
	TokenProvider TokenProvider
	// 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.
	ProjectIDProvider CredentialsPropertyProvider
	// QuotaProjectIDProvider resolves the quota project ID associated with the
	// credentials.
	QuotaProjectIDProvider CredentialsPropertyProvider
	// UniverseDomainProvider resolves the universe domain with the credentials.
	UniverseDomainProvider CredentialsPropertyProvider
}

CredentialsOptions are used to configure [Credentials].

CredentialsPropertyFunc

type CredentialsPropertyFunc func(context.Context) (string, error)

CredentialsPropertyFunc is a type adapter to allow the use of ordinary functions as a [CredentialsPropertyProvider].

func (CredentialsPropertyFunc) GetProperty

func (p CredentialsPropertyFunc) GetProperty(ctx context.Context) (string, error)

GetProperty loads the properly value provided the given context.

CredentialsPropertyProvider

type CredentialsPropertyProvider interface {
	GetProperty(context.Context) (string, error)
}

CredentialsPropertyProvider provides an implementation to fetch a property value for [Credentials].

Error

type Error struct {
	// 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.
	Err error
	// contains filtered or unexported fields
}

Error is a error associated with retrieving a [Token]. It can hold useful additional details for debugging.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Temporary

func (e *Error) Temporary() bool

Temporary returns true if the error is considered temporary and may be able to be retried.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Options2LO

type Options2LO struct {
	// Email is the OAuth2 client ID. This value is set as the "iss" in the
	// JWT.
	Email string
	// 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.
	TokenURL string
	// PrivateKeyID is the ID of the key used to sign the JWT. It is used as the
	// "kid" in the JWT header. Optional.
	PrivateKeyID string
	// Subject is the used for to impersonate a user. It is used as the "sub" in
	// the JWT.m Optional.
	Subject string
	// Scopes specifies requested permissions for the token. Optional.
	Scopes []string
	// Expires specifies the lifetime of the token. Optional.
	Expires time.Duration
	// Audience specifies the "aud" in the JWT. Optional.
	Audience string
	// PrivateClaims allows specifying any custom claims for the JWT. Optional.
	PrivateClaims map[string]interface{}

	// 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.
	UseIDToken bool
}

Options2LO is the configuration settings for doing a 2-legged JWT OAuth2 flow.

Options3LO

type Options3LO struct {
	// ClientID is the application's ID.
	ClientID string
	// ClientSecret is the application's secret. Not required if AuthHandlerOpts
	// is set.
	ClientSecret string
	// AuthURL is the URL for authenticating.
	AuthURL string
	// TokenURL is the URL for retrieving a token.
	TokenURL string
	// AuthStyle is used to describe how to client info in the token request.
	AuthStyle Style
	// RefreshToken is the token used to refresh the credential. Not required
	// if AuthHandlerOpts is set.
	RefreshToken string
	// RedirectURL is the URL to redirect users to. Optional.
	RedirectURL string
	// Scopes specifies requested permissions for the Token. Optional.
	Scopes []string

	// URLParams are the set of values to apply to the token exchange. Optional.
	URLParams url.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 10 seconds. Optional.
	EarlyTokenExpiry time.Duration

	// AuthHandlerOpts provides a set of options for doing a
	// 3-legged OAuth2 flow with a custom [AuthorizationHandler]. Optional.
	AuthHandlerOpts *AuthorizationHandlerOptions
}

Options3LO are the options for doing a 3-legged OAuth2 flow.

PKCEOptions

type PKCEOptions struct {
	// Challenge is the un-padded, base64-url-encoded string of the encrypted code verifier.
	Challenge string // The un-padded, base64-url-encoded string of the encrypted code verifier.
	// ChallengeMethod is the encryption method (ex. S256).
	ChallengeMethod string
	// Verifier is the original, non-encrypted secret.
	Verifier string // The original, non-encrypted secret.
}

PKCEOptions holds parameters to support PKCE.

Style

type Style int

Style describes how the token endpoint wants to receive the ClientID and ClientSecret.

StyleUnknown, StyleInParams, StyleInHeader

const (
	// StyleUnknown means the value has not been initiated. Sending this in
	// a request will cause the token exchange to fail.
	StyleUnknown Style = iota
	// StyleInParams sends client info in the body of a POST request.
	StyleInParams
	// StyleInHeader sends client info using Basic Authorization header.
	StyleInHeader
)

Token

type Token struct {
	// 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.
	Value string
	// Type is the type of token Value is. If uninitialized, it should be
	// assumed to be a "Bearer" token.
	Type string
	// Expiry is the time the token is set to expire.
	Expiry time.Time
	// Metadata  may include, but is not limited to, the body of the token
	// response returned by the server.
	Metadata map[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 are considered read-only.

func (*Token) IsValid

func (t *Token) IsValid() bool

IsValid reports that a [Token] is non-nil, has a [Token.Value], and has not expired. A token is considered expired if [Token.Expiry] has passed or will pass in the next 10 seconds.

TokenProvider

type TokenProvider interface {
	// 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

func New2LOTokenProvider(opts *Options2LO) (TokenProvider, error)

New2LOTokenProvider returns a [TokenProvider] from the provided options.

Example

package main

import (
	"log"

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

func main() {
	// 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)
	if err != nil {
		log.Fatal(err)
	}
	client, err := httptransport.NewClient(&httptransport.Options{
		Credentials: auth.NewCredentials(&auth.CredentialsOptions{
			TokenProvider: tp,
		}),
	})
	if err != nil {
		log.Fatal(err)
	}
	client.Get("...")
	_ = tp
}

func New3LOTokenProvider

func New3LOTokenProvider(opts *Options3LO) (TokenProvider, error)

New3LOTokenProvider returns a [TokenProvider] based on the 3-legged OAuth2 configuration. The TokenProvider is caches and auto-refreshes tokens by default.

func NewCachedTokenProvider

func NewCachedTokenProvider(tp TokenProvider, opts *CachedTokenProviderOptions) TokenProvider

NewCachedTokenProvider wraps a [TokenProvider] to cache the tokens returned by the underlying provider. By default it will refresh tokens ten seconds before they expire, but this time can be configured with the optional options.