auth

package
v0.20241126.1723 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2024 License: MPL-2.0 Imports: 34 Imported by: 0

README

Package: github.com/hashicorp/go-azure-sdk/sdk/auth

This package contains Authorizers which can be used to authenticate calls to the Azure APIs for use with hashicorp/go-azure-sdk.

Example: Authenticating using the Azure CLI

package main

import (
	"context"
	"log"

	"github.com/hashicorp/go-azure-sdk/sdk/auth"
	"github.com/hashicorp/go-azure-sdk/sdk/environments"
)

func main() {
	environment := environments.Public
	credentials := auth.Credentials{
		Environment:                       environment,
		EnableAuthenticatingUsingAzureCLI: true,
	}
	authorizer, err := auth.NewAuthorizerFromCredentials(context.TODO(), credentials, environment.MSGraph)
	if err != nil {
		log.Fatalf("building authorizer from credentials: %+v", err)
	}
	// ...
}

Example: Authenticating using a Client Certificate

package main

import (
	"context"
	"log"

	"github.com/hashicorp/go-azure-sdk/sdk/auth"
	"github.com/hashicorp/go-azure-sdk/sdk/environments"
)

func main() {
	environment := environments.Public
	credentials := auth.Credentials{
		Environment: environment,
		EnableAuthenticatingUsingClientCertificate: true,
		ClientCertificatePath:                      "/path/to/cert.pfx",
		ClientCertificatePassword:                  "somepassword",
	}
	authorizer, err := auth.NewAuthorizerFromCredentials(context.TODO(), credentials, environment.MSGraph)
	if err != nil {
		log.Fatalf("building authorizer from credentials: %+v", err)
	}
	// ..
}

Example: Authenticating using a Client Secret

import (
	"context"
	"log"

	"github.com/hashicorp/go-azure-sdk/sdk/auth"
	"github.com/hashicorp/go-azure-sdk/sdk/environments"
)

func main() {
	environment := environments.Public
	credentials := auth.Credentials{
		Environment:                           environment,
		EnableAuthenticatingUsingClientSecret: true,
		ClientSecret:                          "some-secret-value",
	}
	authorizer, err := auth.NewAuthorizerFromCredentials(context.TODO(), credentials, environment.MSGraph)
	if err != nil {
		log.Fatalf("building authorizer from credentials: %+v", err)
	}
	// ..
}

Example: Authenticating using a Managed Identity

package main

import (
	"context"
	"log"

	"github.com/hashicorp/go-azure-sdk/sdk/auth"
	"github.com/hashicorp/go-azure-sdk/sdk/environments"
)

func main() {
	environment := environments.Public
	credentials := auth.Credentials{
		Environment:                              environment,
		EnableAuthenticatingUsingManagedIdentity: true,
	}
	authorizer, err := auth.NewAuthorizerFromCredentials(context.TODO(), credentials, environment.MSGraph)
	if err != nil {
		log.Fatalf("building authorizer from credentials: %+v", err)
	}
	// ..
}

Example: Authenticating using GitHub OIDC

package main

import (
	"context"
	"log"
	"os"

	"github.com/hashicorp/go-azure-sdk/sdk/auth"
	"github.com/hashicorp/go-azure-sdk/sdk/environments"
)

func main() {
	environment := environments.Public
	credentials := auth.Credentials{
		Environment:                         environment,
		EnableAuthenticationUsingGitHubOIDC: true,
		GitHubOIDCTokenRequestURL:           os.Getenv("ACTIONS_ID_TOKEN_REQUEST_URL"),
		GitHubOIDCTokenRequestToken:         os.Getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN"),
	}
	authorizer, err := auth.NewAuthorizerFromCredentials(context.TODO(), credentials, environment.MSGraph)
	if err != nil {
		log.Fatalf("building authorizer from credentials: %+v", err)
	}
	// ..
}

Example: Authenticating using OIDC

package main

import (
	"context"
	"log"

	"github.com/hashicorp/go-azure-sdk/sdk/auth"
	"github.com/hashicorp/go-azure-sdk/sdk/environments"
)

func main() {
	environment := environments.Public
	credentials := auth.Credentials{
		Environment:                   environment,
		EnableAuthenticationUsingOIDC: true,
		OIDCAssertionToken:            "some-token",
	}
	authorizer, err := auth.NewAuthorizerFromCredentials(context.TODO(), credentials, environment.MSGraph)
	if err != nil {
		log.Fatalf("building authorizer from credentials: %+v", err)
	}
	// ..
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetAuthHeader

func SetAuthHeader(ctx context.Context, req *http.Request, authorizer Authorizer) error

SetAuthHeader decorates a *http.Request with the Authorization header using a bearer token obtained from the Token method of the supplied Authorizer.

Types

type Authorizer

type Authorizer interface {
	// Token obtains a new access token for the configured tenant
	Token(ctx context.Context, request *http.Request) (*oauth2.Token, error)

	// AuxiliaryTokens obtains new access tokens for the configured auxiliary tenants
	AuxiliaryTokens(ctx context.Context, request *http.Request) ([]*oauth2.Token, error)
}

Authorizer is anything that can return an access token for authorizing API connections

func NewAuthorizerFromCredentials

func NewAuthorizerFromCredentials(ctx context.Context, c Credentials, api environments.Api) (Authorizer, error)

NewAuthorizerFromCredentials returns a suitable Authorizer depending on what is defined in the Credentials Authorizers are selected for authentication methods in the following preferential order: - Client certificate authentication - Client secret authentication - OIDC authentication - GitHub OIDC authentication - MSI authentication - Azure CLI authentication

Whether one of these is returned depends on whether it is enabled in the Credentials, and whether sufficient configuration fields are set to enable that authentication method.

For client certificate authentication, specify TenantID, ClientID and ClientCertificateData / ClientCertificatePath. For client secret authentication, specify TenantID, ClientID and ClientSecret. For OIDC authentication, specify TenantID, ClientID and OIDCAssertionToken. For GitHub OIDC authentication, specify TenantID, ClientID, GitHubOIDCTokenRequestURL and GitHubOIDCTokenRequestToken. MSI authentication (if enabled) using the Azure Metadata Service is then attempted Azure CLI authentication (if enabled) is attempted last

It's recommended to only enable the mechanisms you have configured and are known to work in the execution environment. If any authentication mechanism fails due to misconfiguration or some other error, the function will return (nil, error) and later mechanisms will not be attempted.

func NewAzureCliAuthorizer

func NewAzureCliAuthorizer(ctx context.Context, options AzureCliAuthorizerOptions) (Authorizer, error)

NewAzureCliAuthorizer returns an Authorizer which authenticates using the Azure CLI.

func NewClientCertificateAuthorizer

func NewClientCertificateAuthorizer(ctx context.Context, options ClientCertificateAuthorizerOptions) (Authorizer, error)

NewClientCertificateAuthorizer returns an authorizer which uses client certificate authentication.

func NewClientSecretAuthorizer

func NewClientSecretAuthorizer(ctx context.Context, options ClientSecretAuthorizerOptions) (Authorizer, error)

NewClientSecretAuthorizer returns an authorizer which uses client secret authentication.

func NewGitHubOIDCAuthorizer

func NewGitHubOIDCAuthorizer(ctx context.Context, options GitHubOIDCAuthorizerOptions) (Authorizer, error)

NewGitHubOIDCAuthorizer returns an authorizer which acquires a client assertion from a GitHub endpoint, then uses client assertion authentication to obtain an access token.

func NewManagedIdentityAuthorizer

func NewManagedIdentityAuthorizer(ctx context.Context, options ManagedIdentityAuthorizerOptions) (Authorizer, error)

NewManagedIdentityAuthorizer returns an authorizer using a Managed Identity for authentication.

func NewOIDCAuthorizer

func NewOIDCAuthorizer(ctx context.Context, options OIDCAuthorizerOptions) (Authorizer, error)

NewOIDCAuthorizer returns an authorizer which uses OIDC authentication (federated client credentials)

type AzureCliAuthorizer

type AzureCliAuthorizer struct {
	// TenantID is the specified tenant ID, or the auto-detected tenant ID if none was specified
	TenantID string

	// DefaultSubscriptionID is the default subscription, when detected
	DefaultSubscriptionID string

	// SubscriptionIDHint is a user-provided subscription ID used to hint to Azure CLI which account to select
	SubscriptionIDHint string
	// contains filtered or unexported fields
}

AzureCliAuthorizer is an Authorizer which supports the Azure CLI.

func (*AzureCliAuthorizer) AuxiliaryTokens

func (a *AzureCliAuthorizer) AuxiliaryTokens(_ context.Context, _ *http.Request) ([]*oauth2.Token, error)

AuxiliaryTokens returns additional tokens for auxiliary tenant IDs, for use in multi-tenant scenarios

func (*AzureCliAuthorizer) Token

Token returns an access token using the Azure CLI as an authentication mechanism.

type AzureCliAuthorizerOptions

type AzureCliAuthorizerOptions struct {
	// Api describes the Azure API being used
	Api environments.Api

	// TenantId is the tenant to authenticate against
	TenantId string

	// AuxTenantIds lists additional tenants to authenticate against, currently only
	// used for Resource Manager when auxiliary tenants are needed.
	// e.g. https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant
	AuxTenantIds []string

	// SubscriptionIdHint is the subscription to target when selecting an account with which to obtain an access token
	// Used to hint to Azure CLI which of its signed-in accounts it should select, based on apparent access to the subscription.
	SubscriptionIdHint string
}

type CachedAuthorizer

type CachedAuthorizer struct {
	// Source contains the underlying Authorizer for obtaining tokens
	Source Authorizer
	// contains filtered or unexported fields
}

CachedAuthorizer caches a token until it expires, then acquires a new token from Source

func (*CachedAuthorizer) AuxiliaryTokens

func (c *CachedAuthorizer) AuxiliaryTokens(ctx context.Context, req *http.Request) ([]*oauth2.Token, error)

AuxiliaryTokens returns additional tokens for auxiliary tenant IDs, for use in multi-tenant scenarios

func (*CachedAuthorizer) InvalidateCachedTokens

func (c *CachedAuthorizer) InvalidateCachedTokens() error

InvalidateCachedTokens expires the currently cached token and auxTokens, forcing new tokens to be acquired when Token() or AuxiliaryTokens() are next called

func (*CachedAuthorizer) Token

func (c *CachedAuthorizer) Token(ctx context.Context, req *http.Request) (*oauth2.Token, error)

Token returns the current token if it's still valid, else will acquire a new token

type CachingAuthorizer

type CachingAuthorizer interface {
	Authorizer

	// InvalidateCachedTokens invalidates any cached access tokens, so that new tokens are automatically
	// retrieved from the authorization service on the next call to Token or AuxiliaryTokens.
	InvalidateCachedTokens() error
}

CachingAuthorizer implements Authorizer whilst caching access tokens and offering a way to intentionally invalidate them

func NewCachedAuthorizer

func NewCachedAuthorizer(src Authorizer) (CachingAuthorizer, error)

NewCachedAuthorizer returns an Authorizer that caches an access token for the duration of its validity. If the cached token expires, a new one is acquired and cached.

type ClientAssertionAuthorizer

type ClientAssertionAuthorizer struct {
	// contains filtered or unexported fields
}

func (*ClientAssertionAuthorizer) AuxiliaryTokens

func (a *ClientAssertionAuthorizer) AuxiliaryTokens(ctx context.Context, _ *http.Request) ([]*oauth2.Token, error)

AuxiliaryTokens returns additional tokens for auxiliary tenant IDs, for use in multi-tenant scenarios

func (*ClientAssertionAuthorizer) Token

type ClientCertificateAuthorizerOptions

type ClientCertificateAuthorizerOptions struct {
	// Environment is the Azure environment/cloud being targeted
	Environment environments.Environment

	// Api describes the Azure API being used
	Api environments.Api

	// TenantId is the tenant to authenticate against
	TenantId string

	// AuxTenantIds lists additional tenants to authenticate against, currently only
	// used for Resource Manager when auxiliary tenants are needed.
	// e.g. https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant
	AuxTenantIds []string

	// ClientId is the client ID used when authenticating
	ClientId string

	// Pkcs12Data is the binary PKCS#12 archive data containing the certificate and private key
	Pkcs12Data []byte

	// Pkcs12Path is a path to a binary PKCS#12 archive on the filesystem
	Pkcs12Path string

	// Pkcs12Pass is the challenge passphrase to decrypt the PKCS#12 archive
	Pkcs12Pass string
}

type ClientSecretAuthorizer

type ClientSecretAuthorizer struct {
	// contains filtered or unexported fields
}

func (*ClientSecretAuthorizer) AuxiliaryTokens

func (a *ClientSecretAuthorizer) AuxiliaryTokens(ctx context.Context, _ *http.Request) ([]*oauth2.Token, error)

AuxiliaryTokens returns additional tokens for auxiliary tenant IDs, for use in multi-tenant scenarios

func (*ClientSecretAuthorizer) Token

type ClientSecretAuthorizerOptions

type ClientSecretAuthorizerOptions struct {
	// Environment is the Azure environment/cloud being targeted
	Environment environments.Environment

	// Api describes the Azure API being used
	Api environments.Api

	// TenantId is the tenant to authenticate against
	TenantId string

	// AuxTenantIds lists additional tenants to authenticate against, currently only
	// used for Resource Manager when auxiliary tenants are needed.
	// e.g. https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant
	AuxTenantIds []string

	// ClientId is the client ID used when authenticating
	ClientId string

	// ClientSecret is the client secret used when authenticating
	ClientSecret string
}

type Credentials

type Credentials struct {
	// Specifies the national cloud environment to use
	Environment environments.Environment

	// AuxiliaryTenantIDs specifies the Auxiliary Tenant IDs for which to obtain tokens in a multi-tenant scenario.
	AuxiliaryTenantIDs []string
	// ClientID specifies the Client ID for the application used to authenticate the connection
	ClientID string
	// TenantID specifies the Azure Active Directory Tenant to connect to, which must be a valid UUID.
	TenantID string

	// EnableAuthenticatingUsingAzureCLI specifies whether Azure CLI authentication should be checked.
	EnableAuthenticatingUsingAzureCLI bool
	// AzureCliSubscriptionIDHint is the subscription to target when selecting an account with which to obtain an access token
	// Used to hint to Azure CLI which of its signed-in accounts it should select, based on apparent access to the subscription.
	AzureCliSubscriptionIDHint string

	// EnableAuthenticatingUsingClientCertificate specifies whether Client Certificate authentication should be checked.
	EnableAuthenticatingUsingClientCertificate bool
	// ClientCertificateData specifies the contents of a Client Certificate PKCS#12 bundle.
	ClientCertificateData []byte
	// ClientCertificatePath specifies the path to a Client Certificate PKCS#12 bundle (.pfx file)
	ClientCertificatePath string
	// ClientCertificatePassword specifies the encryption password to unlock a Client Certificate.
	ClientCertificatePassword string

	// EnableAuthenticatingUsingClientSecret specifies whether Client Secret authentication should be used.
	EnableAuthenticatingUsingClientSecret bool
	// ClientSecret specifies the Secret used authenticate using Client Secret authentication.
	ClientSecret string

	// EnableAuthenticatingUsingManagedIdentity specifies whether Managed Identity authentication should be checked.
	EnableAuthenticatingUsingManagedIdentity bool
	// CustomManagedIdentityEndpoint specifies a custom endpoint which should be used for Managed Identity.
	CustomManagedIdentityEndpoint string

	// Enables OIDC authentication (federated client credentials).
	EnableAuthenticationUsingOIDC bool
	// OIDCAssertionToken specifies the OIDC Assertion Token to authenticate using Client Credentials.
	OIDCAssertionToken string

	// EnableAuthenticationUsingGitHubOIDC specifies whether GitHub OIDC
	EnableAuthenticationUsingGitHubOIDC bool
	// GitHubOIDCTokenRequestURL specifies the URL for GitHub's OIDC provider
	GitHubOIDCTokenRequestURL string
	// GitHubOIDCTokenRequestToken specifies the bearer token for the request to GitHub's OIDC provider
	GitHubOIDCTokenRequestToken string
}

Credentials sets up NewAuthorizer to return an Authorizer based on the provided credentails.

type GitHubOIDCAuthorizer

type GitHubOIDCAuthorizer struct {
	// contains filtered or unexported fields
}

func (*GitHubOIDCAuthorizer) AuxiliaryTokens

func (a *GitHubOIDCAuthorizer) AuxiliaryTokens(ctx context.Context, req *http.Request) ([]*oauth2.Token, error)

func (*GitHubOIDCAuthorizer) Token

type GitHubOIDCAuthorizerOptions

type GitHubOIDCAuthorizerOptions struct {
	// Api describes the Azure API being used
	Api environments.Api

	// ClientId is the client ID used when authenticating
	ClientId string

	// Environment is the Azure environment/cloud being targeted
	Environment environments.Environment

	// TenantId is the tenant to authenticate against
	TenantId string

	// AuxiliaryTenantIds lists additional tenants to authenticate against, currently only
	// used for Resource Manager when auxiliary tenants are needed.
	// e.g. https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant
	AuxiliaryTenantIds []string

	// IdTokenRequestUrl is the URL for the OIDC provider from which to request an ID token.
	// Usually exposed via the ACTIONS_ID_TOKEN_REQUEST_URL environment variable when running in GitHub Actions
	IdTokenRequestUrl string

	// IdTokenRequestToken is the bearer token for the request to the OIDC provider.
	// Usually exposed via the ACTIONS_ID_TOKEN_REQUEST_TOKEN environment variable when running in GitHub Actions
	IdTokenRequestToken string
}

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is an HTTP client used for sending authentication requests and obtaining tokens

var (
	// Client is the HTTP client used for sending authentication requests and obtaining tokens
	Client HTTPClient

	// MetadataClient is the HTTP client used for obtaining tokens from the Instance Metadata Service
	MetadataClient HTTPClient
)

type ManagedIdentityAuthorizer

type ManagedIdentityAuthorizer struct {
	// contains filtered or unexported fields
}

ManagedIdentityAuthorizer is an Authorizer which supports managed service identity.

func (*ManagedIdentityAuthorizer) AuxiliaryTokens

func (a *ManagedIdentityAuthorizer) AuxiliaryTokens(_ context.Context, _ *http.Request) ([]*oauth2.Token, error)

AuxiliaryTokens returns additional tokens for auxiliary tenant IDs, for use in multi-tenant scenarios

func (*ManagedIdentityAuthorizer) Token

Token returns an access token acquired from the metadata endpoint.

type ManagedIdentityAuthorizerOptions

type ManagedIdentityAuthorizerOptions struct {
	// Api describes the Azure API being used
	Api environments.Api

	// ClientId is the client ID used when authenticating
	ClientId string

	// CustomManagedIdentityEndpoint is an optional endpoint from which to obtain an access
	// token. When blank, the default is used.
	CustomManagedIdentityEndpoint string
}

type OIDCAuthorizerOptions

type OIDCAuthorizerOptions struct {
	// Environment is the Azure environment/cloud being targeted
	Environment environments.Environment

	// Api describes the Azure API being used
	Api environments.Api

	// TenantId is the tenant to authenticate against
	TenantId string

	// AuxiliaryTenantIds lists additional tenants to authenticate against, currently only
	// used for Resource Manager when auxiliary tenants are needed.
	// e.g. https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant
	AuxiliaryTenantIds []string

	// ClientId is the client ID used when authenticating
	ClientId string

	// FederatedAssertion is the client assertion dispensed by the OIDC provider used to verify identity during authentication
	FederatedAssertion string
}

type SharedKeyAuthorizer

type SharedKeyAuthorizer struct {
	// contains filtered or unexported fields
}

func NewSharedKeyAuthorizer

func NewSharedKeyAuthorizer(accountName string, accountKey string, keyType SharedKeyType) (*SharedKeyAuthorizer, error)

func (*SharedKeyAuthorizer) AuxiliaryTokens

func (s *SharedKeyAuthorizer) AuxiliaryTokens(_ context.Context, _ *http.Request) ([]*oauth2.Token, error)

func (*SharedKeyAuthorizer) Token

func (s *SharedKeyAuthorizer) Token(ctx context.Context, req *http.Request) (*oauth2.Token, error)

type SharedKeyType

type SharedKeyType string

SharedKeyType defines the enumeration for the various shared key types. See https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key for details on the shared key types.

const (
	SharedKey      SharedKeyType = "sharedKey"
	SharedKeyTable SharedKeyType = "sharedKeyTable"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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