auth

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: Apache-2.0 Imports: 14 Imported by: 4

README

auth

This module is currently EXPERIMENTAL and under active development. It is not yet intended to be used.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type 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.

type 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.

type 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.

type Credentials added in v0.2.0

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

Credentials holds Google credentials, including [Application Default Credentials](https://developers.google.com/accounts/docs/application-default-credentials).

func NewCredentials added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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

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

func (*Credentials) QuotaProjectID added in v0.2.0

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 added in v0.2.0

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".

type CredentialsOptions added in v0.2.0

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.

type CredentialsPropertyFunc added in v0.2.0

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 added in v0.2.0

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

GetProperty loads the properly value provided the given context.

type CredentialsPropertyProvider added in v0.2.0

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

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

type 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

type 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.

type 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.

type 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.

type Style

type Style int

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

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
)

type 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.

type 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
}
Output:

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.

Directories

Path Synopsis
Package credentials provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs.
Package credentials provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs.
downscope
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.
externalaccount
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.
impersonate
Package impersonate is used to impersonate Google Credentials.
Package impersonate is used to impersonate Google Credentials.
credsfile
Package credsfile is meant to hide implementation details from the pubic surface of the detect package.
Package credsfile is meant to hide implementation details from the pubic surface of the detect package.
jwt
testutil/testdns
Package testdns is a light DNS client used for testings to avoid pulling in dependencies.
Package testdns is a light DNS client used for testings to avoid pulling in dependencies.
testutil/testgcs
Package testgcs is a light GCS client used for testings to avoid pulling in dependencies.
Package testgcs is a light GCS client used for testings to avoid pulling in dependencies.
transport
Package transport provided internal helpers for the two transport packages (grpctransport and httptransport).
Package transport provided internal helpers for the two transport packages (grpctransport and httptransport).
transport/cert/cmd
test_signer.go is a net/rpc server that listens on stdin/stdout, exposing mock methods for testing enterprise certificate proxy flow.
test_signer.go is a net/rpc server that listens on stdin/stdout, exposing mock methods for testing enterprise certificate proxy flow.
oauth2adapt module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL