Movatterモバイル変換


[0]ホーム

URL:


auth

packagemodule
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:16Imported by:26

Details

Repository

github.com/googleapis/google-cloud-go

Links

README

Google Auth Library for Go

Go Reference

Install

go get cloud.google.com/go/auth@latest

Usage

The most common way this library is used is transitively, by default, from anyof our Go client libraries.

Notable use-cases
  • To create a credential directly please see examples in thecredentialspackage.
  • To create a authenticated HTTP client please see examples in thehttptransportpackage.
  • To create a authenticated gRPC connection please see examples in thegrpctransportpackage.
  • To create an ID token please see examples in theidtokenpackage.

Contributing

Contributions are welcome. Please, see theCONTRIBUTINGdocument for details.

Please note that this project is released with a Contributor Code of Conduct.By participating in this project you agree to abide by its terms.SeeContributor Code of Conductfor more information.

Documentation

Overview

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.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

typeAuthorizationHandler

type AuthorizationHandler func(authCodeURLstring) (codestring, statestring, errerror)

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.

typeAuthorizationHandlerOptions

type AuthorizationHandlerOptions struct {// 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 customAuthorizationHandler.

typeCachedTokenProviderOptions

type CachedTokenProviderOptions struct {// 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 cachedTokenProvider.

typeCredentialsadded inv0.2.0

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

Credentials holds Google credentials, includingApplication Default Credentials.

funcNewCredentialsadded inv0.2.0

func NewCredentials(opts *CredentialsOptions) *Credentials

NewCredentials returns newCredentials from the provided options.

func (*Credentials)JSONadded inv0.2.0

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

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

func (*Credentials)ProjectIDadded inv0.2.0

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

ProjectID returns the associated project ID from the underlying file orenvironment.

func (*Credentials)QuotaProjectIDadded inv0.2.0

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

QuotaProjectID returns the associated quota project ID from the underlyingfile or environment.

func (*Credentials)UniverseDomainadded inv0.2.0

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

typeCredentialsOptionsadded inv0.2.0

type CredentialsOptions struct {// 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 configureCredentials.

typeCredentialsPropertyFuncadded inv0.2.0

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

CredentialsPropertyFunc is a type adapter to allow the use of ordinaryfunctions as aCredentialsPropertyProvider.

func (CredentialsPropertyFunc)GetPropertyadded inv0.2.0

GetProperty loads the properly value provided the given context.

typeCredentialsPropertyProvideradded inv0.2.0

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

CredentialsPropertyProvider provides an implementation to fetch a propertyvalue forCredentials.

typeError

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.Errerror// contains filtered or unexported fields}

Error is a error associated with retrieving aToken. It can hold usefuladditional 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 ableto be retried.

func (*Error)Unwrap

func (e *Error) Unwrap()error

typeOptions2LO

type Options2LO struct {// 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.PrivateClaims map[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.

typeOptions3LO

type Options3LO struct {// 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.

typePKCEOptions

type PKCEOptions struct {// 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.

typeStyle

type Styleint

Style describes how the token endpoint wants to receive the ClientID andClientSecret.

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)

typeToken

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.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.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 areconsidered read-only.

func (*Token)IsValid

func (t *Token) IsValid()bool

IsValid reports that aToken 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)MetadataStringadded inv0.7.3

func (t *Token) MetadataString(kstring)string

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.

typeTokenProvider

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.

funcNew2LOTokenProvider

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

New2LOTokenProvider returns aTokenProvider from the provided options.

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

funcNew3LOTokenProvider

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

New3LOTokenProvider returns aTokenProvider based on the 3-legged OAuth2configuration. The TokenProvider is caches and auto-refreshes tokens bydefault.

funcNewCachedTokenProvider

func NewCachedTokenProvider(tpTokenProvider, opts *CachedTokenProviderOptions)TokenProvider

NewCachedTokenProvider wraps aTokenProvider to cache the tokens returnedby the underlying provider. By default it will refresh tokens asynchronouslya few minutes before they expire.

Source Files

View all Source files

Directories

PathSynopsis
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.
idtoken
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.
impersonate
Package impersonate is used to impersonate Google Credentials.
Package impersonate is used to impersonate Google Credentials.
Package grpctransport provides functionality for managing gRPC client connections to Google Cloud services.
Package grpctransport provides functionality for managing gRPC client connections to Google Cloud services.
Package httptransport provides functionality for managing HTTP client connections to Google Cloud services.
Package httptransport provides functionality for managing HTTP client connections to Google Cloud services.
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.
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/cmdcommand
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.

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