Documentation
¶
Overview ¶
Package idtoken provides functionality for generating and validating ID tokens, with configurable options for audience, custom claims, and token formats.
For more information on ID tokens, see https://cloud.google.com/docs/authentication/token-types#id.
Index ¶
- func NewCredentials(opts *Options) (*auth.Credentials, error)
- func NewCredentialsFromFile(credType credentials.CredType, filename string, opts *Options) (*auth.Credentials, error)
- func NewCredentialsFromJSON(credType credentials.CredType, b []byte, opts *Options) (*auth.Credentials, error)
- type ComputeTokenFormat
- type Options
- type Payload
- type Validator
- type ValidatorOptions
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NewCredentials ¶
func NewCredentials(opts *Options) (*auth.Credentials, error)
NewCredentials creates a cloud.google.com/go/auth.Credentials that returns ID tokens configured by the opts provided. The parameter opts.Audience must not be empty. If both opts.CredentialsFile and opts.CredentialsJSON are empty, an attempt will be made to detect credentials from the environment (see cloud.google.com/go/auth/credentials.DetectDefault). Only service account, impersonated service account, external account and Compute credentials are supported.
Example (SetAuthorizationHeader) ¶
package main
import (
"context"
"net/http"
"cloud.google.com/go/auth/credentials/idtoken"
"cloud.google.com/go/auth/httptransport"
)
func main() {
ctx := context.Background()
audience := "http://example.com"
creds, err := idtoken.NewCredentials(&idtoken.Options{
Audience: audience,
})
if err != nil {
// Handle error.
}
token, err := creds.Token(ctx)
if err != nil {
// Handle error.
}
req, err := http.NewRequest(http.MethodGet, audience, nil)
if err != nil {
// Handle error.
}
httptransport.SetAuthHeader(token, req)
}
func NewCredentialsFromFile ¶ added in v0.18.0
func NewCredentialsFromFile(credType credentials.CredType, filename string, opts *Options) (*auth.Credentials, error)
NewCredentialsFromFile creates a cloud.google.com/go/auth.Credentials that returns ID tokens from the provided file. The credType argument specifies the expected credential type. If the file content does not match the expected type, an error is returned.
This method is safe to use with untrusted credential configurations if the expected credType is NOT credentials.ExternalAccount or credentials.ImpersonatedServiceAccount.
**IMPORTANT**: If you use credentials.ExternalAccount or credentials.ImpersonatedServiceAccount, you must validate the credential configuration before providing it to this method. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to [Validate credential configurations from external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).
func NewCredentialsFromJSON ¶ added in v0.18.0
func NewCredentialsFromJSON(credType credentials.CredType, b []byte, opts *Options) (*auth.Credentials, error)
NewCredentialsFromJSON creates a cloud.google.com/go/auth.Credentials that returns ID tokens from the provided JSON bytes. The credType argument specifies the expected credential type. If the JSON does not match the expected type, an error is returned.
This method is safe to use with untrusted credential configurations if the expected credType is NOT credentials.ExternalAccount or credentials.ImpersonatedServiceAccount.
**IMPORTANT**: If you use credentials.ExternalAccount or credentials.ImpersonatedServiceAccount, you must validate the credential configuration before providing it to this method. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to [Validate credential configurations from external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).
Types ¶
type ComputeTokenFormat ¶
type ComputeTokenFormat int
ComputeTokenFormat dictates the the token format when requesting an ID token from the compute metadata service.
const ( // ComputeTokenFormatDefault means the same as [ComputeTokenFormatFull]. ComputeTokenFormatDefault ComputeTokenFormat = iota // ComputeTokenFormatStandard mean only standard JWT fields will be included // in the token. ComputeTokenFormatStandard // ComputeTokenFormatFull means the token will include claims about the // virtual machine instance and its project. ComputeTokenFormatFull // ComputeTokenFormatFullWithLicense means the same as // [ComputeTokenFormatFull] with the addition of claims about licenses // associated with the instance. ComputeTokenFormatFullWithLicense )
type Options ¶
type Options struct {
// Audience is the `aud` field for the token, such as an API endpoint the
// token will grant access to. Required.
Audience string
// ComputeTokenFormat dictates the the token format when requesting an ID
// token from the compute metadata service. Optional.
ComputeTokenFormat ComputeTokenFormat
// CustomClaims specifies private non-standard claims for an ID token.
// Optional.
CustomClaims map[string]interface{}
// CredentialsFile sources a JSON credential file from the provided
// filepath. If provided, do not provide CredentialsJSON. 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 := idtoken.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-credentials
CredentialsFile string
// CredentialsJSON sources a JSON credential file from the provided bytes.
// If provided, do not provide CredentialsJSON. 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 := idtoken.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-credentials
CredentialsJSON []byte
// Client configures the underlying client used to make network requests
// when fetching tokens. If provided this should be a fully-authenticated
// client. Optional.
Client *http.Client
// UniverseDomain is the default service domain for a given Cloud universe.
// The default value is "googleapis.com". This is the universe domain
// configured for the client, which will be compared to the universe domain
// that is separately configured for the credentials. Optional.
UniverseDomain string
// 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
}
Options for the configuration of creation of an ID token with NewCredentials.
type Payload ¶
type Payload struct {
Issuer string `json:"iss"`
Audience string `json:"aud"`
Expires int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
Subject string `json:"sub,omitempty"`
Claims map[string]interface{} `json:"-"`
}
Payload represents a decoded payload of an ID token.
func ParsePayload ¶
ParsePayload parses the given token and returns its payload.
Warning: This function does not validate the token prior to parsing it.
ParsePayload is primarily meant to be used to inspect a token's payload. This is useful when validation fails and the payload needs to be inspected.
Note: A successful Validate() invocation with the same token will return an identical payload.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator provides a way to validate Google ID Tokens
func NewValidator ¶
func NewValidator(opts *ValidatorOptions) (*Validator, error)
NewValidator creates a Validator that uses the options provided to configure a the internal http.Client that will be used to make requests to fetch JWKs.
func (*Validator) Validate ¶
func (v *Validator) Validate(ctx context.Context, idToken string, audience string) (*Payload, error)
Validate is used to validate the provided idToken with a known Google cert URL. If audience is not empty the audience claim of the Token is validated. Upon successful validation a parsed token Payload is returned allowing the caller to validate any additional claims.
type ValidatorOptions ¶
type ValidatorOptions struct {
// Client used to make requests to the certs URL. Optional.
Client *http.Client
// Custom certs URL for RS256 JWK to be used. If not provided, the default
// Google oauth2 endpoint will be used. Optional.
RS256CertsURL string
// Custom certs URL for ES256 JWK to be used. If not provided, the default
// Google IAP endpoint will be used. Optional.
ES256CertsURL string
// 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
}
ValidatorOptions provides a way to configure a Validator.