azidentity

package module
v1.5.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2023 License: MIT Imports: 32 Imported by: 2,034

README

Azure Identity Client Module for Go

The Azure Identity module provides Azure Active Directory (Azure AD) token authentication support across the Azure SDK. It includes a set of TokenCredential implementations, which can be used with Azure SDK clients supporting token authentication.

PkgGoDev | Azure Active Directory documentation | Source code

Getting started

Install the module

This project uses Go modules for versioning and dependency management.

Install the Azure Identity module:

go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity

Prerequisites

Authenticating during local development

When debugging and executing code locally, developers typically use their own accounts to authenticate calls to Azure services. The azidentity module supports authenticating through developer tools to simplify local development.

Authenticating via the Azure CLI

DefaultAzureCredential and AzureCLICredential can authenticate as the user signed in to the Azure CLI. To sign in to the Azure CLI, run az login. On a system with a default web browser, the Azure CLI will launch the browser to authenticate a user.

When no default browser is available, az login will use the device code authentication flow. This can also be selected manually by running az login --use-device-code.

Authenticate via the Azure Developer CLI

Developers coding outside of an IDE can also use the Azure Developer CLI to authenticate. Applications using the DefaultAzureCredential or the AzureDeveloperCLICredential can use the account logged in to the Azure Developer CLI to authenticate calls in their application when running locally.

To authenticate with the Azure Developer CLI, run azd auth login. On a system with a default web browser, azd will launch the browser to authenticate. On systems without a default web browser, run azd auth login --use-device-code to use the device code authentication flow.

Key concepts

Credentials

A credential is a type which contains or can obtain the data needed for a service client to authenticate requests. Service clients across the Azure SDK accept a credential instance when they are constructed, and use that credential to authenticate requests.

The azidentity module focuses on OAuth authentication with Azure Active Directory (AAD). It offers a variety of credential types capable of acquiring an Azure AD access token. See Credential Types for a list of this module's credential types.

DefaultAzureCredential

DefaultAzureCredential is appropriate for most apps that will be deployed to Azure. It combines common production credentials with development credentials. It attempts to authenticate via the following mechanisms in this order, stopping when one succeeds:

DefaultAzureCredential authentication flow

  1. Environment - DefaultAzureCredential will read account information specified via environment variables and use it to authenticate.
  2. Workload Identity - If the app is deployed on Kubernetes with environment variables set by the workload identity webhook, DefaultAzureCredential will authenticate the configured identity.
  3. Managed Identity - If the app is deployed to an Azure host with managed identity enabled, DefaultAzureCredential will authenticate with it.
  4. Azure CLI - If a user or service principal has authenticated via the Azure CLI az login command, DefaultAzureCredential will authenticate that identity.
  5. Azure Developer CLI - If the developer has authenticated via the Azure Developer CLI azd auth login command, the DefaultAzureCredential will authenticate with that account.

Note: DefaultAzureCredential is intended to simplify getting started with the SDK by handling common scenarios with reasonable default behaviors. Developers who want more control or whose scenario isn't served by the default settings should use other credential types.

Managed Identity

DefaultAzureCredential and ManagedIdentityCredential support managed identity authentication in any hosting environment which supports managed identities, such as (this list is not exhaustive):

Examples

Authenticate with DefaultAzureCredential

This example demonstrates authenticating a client from the armresources module with DefaultAzureCredential.

cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
  // handle error
}

client := armresources.NewResourceGroupsClient("subscription ID", cred, nil)
Specify a user-assigned managed identity for DefaultAzureCredential

To configure DefaultAzureCredential to authenticate a user-assigned managed identity, set the environment variable AZURE_CLIENT_ID to the identity's client ID.

Define a custom authentication flow with ChainedTokenCredential

DefaultAzureCredential is generally the quickest way to get started developing apps for Azure. For more advanced scenarios, ChainedTokenCredential links multiple credential instances to be tried sequentially when authenticating. It will try each chained credential in turn until one provides a token or fails to authenticate due to an error.

The following example demonstrates creating a credential, which will attempt to authenticate using managed identity. It will fall back to authenticating via the Azure CLI when a managed identity is unavailable.

managed, err := azidentity.NewManagedIdentityCredential(nil)
if err != nil {
  // handle error
}
azCLI, err := azidentity.NewAzureCLICredential(nil)
if err != nil {
  // handle error
}
chain, err := azidentity.NewChainedTokenCredential([]azcore.TokenCredential{managed, azCLI}, nil)
if err != nil {
  // handle error
}

client := armresources.NewResourceGroupsClient("subscription ID", chain, nil)

Credential Types

Authenticating Azure Hosted Applications
Credential Usage
DefaultAzureCredential Simplified authentication experience for getting started developing Azure apps
ChainedTokenCredential Define custom authentication flows, composing multiple credentials
EnvironmentCredential Authenticate a service principal or user configured by environment variables
ManagedIdentityCredential Authenticate the managed identity of an Azure resource
WorkloadIdentityCredential Authenticate a workload identity on Kubernetes
Authenticating Service Principals
Credential Usage
ClientAssertionCredential Authenticate a service principal with a signed client assertion
ClientCertificateCredential Authenticate a service principal with a certificate
ClientSecretCredential Authenticate a service principal with a secret
Authenticating Users
Credential Usage
InteractiveBrowserCredential Interactively authenticate a user with the default web browser
DeviceCodeCredential Interactively authenticate a user on a device with limited UI
UsernamePasswordCredential Authenticate a user with a username and password
Authenticating via Development Tools
Credential Usage
AzureCLICredential Authenticate as the user signed in to the Azure CLI
AzureDeveloperCLICredential Authenticates as the user signed in to the Azure Developer CLI

Environment Variables

DefaultAzureCredential and EnvironmentCredential can be configured with environment variables. Each type of authentication requires values for specific variables:

Service principal with secret
variable name value
AZURE_CLIENT_ID ID of an Azure Active Directory application
AZURE_TENANT_ID ID of the application's Azure Active Directory tenant
AZURE_CLIENT_SECRET one of the application's client secrets
Service principal with certificate
variable name value
AZURE_CLIENT_ID ID of an Azure Active Directory application
AZURE_TENANT_ID ID of the application's Azure Active Directory tenant
AZURE_CLIENT_CERTIFICATE_PATH path to a certificate file including private key
AZURE_CLIENT_CERTIFICATE_PASSWORD password of the certificate file, if any
Username and password
variable name value
AZURE_CLIENT_ID ID of an Azure Active Directory application
AZURE_USERNAME a username (usually an email address)
AZURE_PASSWORD that user's password

Configuration is attempted in the above order. For example, if values for a client secret and certificate are both present, the client secret will be used.

Troubleshooting

Error Handling

Credentials return an error when they fail to authenticate or lack data they require to authenticate. For guidance on resolving errors from specific credential types, see the troubleshooting guide.

For more details on handling specific Azure Active Directory errors please refer to the Azure Active Directory error code documentation.

Logging

This module uses the classification-based logging implementation in azcore. To enable console logging for all SDK modules, set AZURE_SDK_GO_LOGGING to all. Use the azcore/log package to control log event output or to enable logs for azidentity only. For example:

import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"

// print log output to stdout
azlog.SetListener(func(event azlog.Event, s string) {
    fmt.Println(s)
})

// include only azidentity credential logs
azlog.SetEvents(azidentity.EventAuthentication)

Credentials log basic information only, such as GetToken success or failure and errors. These log entries don't contain authentication secrets but may contain sensitive information.

Next steps

Client and management modules listed on the Azure SDK releases page support authenticating with azidentity credential types. You can learn more about using these libraries in their documentation, which is linked from the release page.

Provide Feedback

If you encounter bugs or have suggestions, please open an issue.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Impressions

Documentation

Overview

Example (PersistentCache)

Credentials, excepting those that authenticate via external tools like AzureCLICredential, cache authentication data in memory by default. Most of these credentials also support optional persistent caching. This example shows how to enable and configure that for a credential. It shows only InteractiveBrowserCredential, however all credentials that support persistent caching have the same TokenCachePersistenceOptions API.

package main

import (
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"

	// importing the cache module registers the cache implementation for the current platform
	_ "github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache"
)

func main() {
	cred, err := azidentity.NewInteractiveBrowserCredential(&azidentity.InteractiveBrowserCredentialOptions{
		// Non-nil TokenCachePersistenceOptions enables persistent caching with default options.
		// See TokenCachePersistenceOptions documentation for details of the supported options.
		TokenCachePersistenceOptions: &azidentity.TokenCachePersistenceOptions{},
	})
	if err != nil {
		// TODO: handle error
	}
	// TODO: use credential
	_ = cred
}
Output:

Example (UserAuthentication)

This example shows how to authenticate a user with InteractiveBrowserCredential, enabling persistent caching so that the user doesn't need to authenticate interactively the next time the application runs.

package main

import (
	"context"
	"encoding/json"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

func main() {
	cred, err := azidentity.NewInteractiveBrowserCredential(&azidentity.InteractiveBrowserCredentialOptions{
		// By default, credentials begin interactive authentication whenever necessary. To instead control when
		// a credential prompts for user interaction, set this option true. The credential will then return
		// azidentity.ErrAuthenticationRequired instead of prompting for authentication. The application
		// can then call the credential's Authenticate method when it's convenient to prompt the user.
		DisableAutomaticAuthentication: true,

		// By default, credentials cache in memory. Set TokenCachePersistenceOptions to enable persistent caching.
		TokenCachePersistenceOptions: &azidentity.TokenCachePersistenceOptions{
			// optionally set Name to isolate this credential's cache from other applications
			Name: "myapp",
		},
	})
	if err != nil {
		// TODO: handle error
	}

	// The Authenticate method begins interactive authentication. Call it whenever it's convenient for
	// your application to authenticate a user. If Authenticate succeeds, the credential is ready for
	// use with a client.
	record, err := cred.Authenticate(context.TODO(), nil)
	if err != nil {
		// TODO: handle error
	}

	// The record contains no authentication secrets. You can marshal it for storage.
	b, err := json.Marshal(record)
	if err != nil {
		// TODO: handle error
	}
	// TODO: store bytes
	_ = b

	// An authentication record stored by your application enables other credentials to access data from
	// past authentications. If the cache contains sufficient data, your application won't need to prompt
	// for authentication.
	var unmarshaled azidentity.AuthenticationRecord
	err = json.Unmarshal(b, &unmarshaled)
	if err != nil {
		// TODO: handle error
	}

	// this credential will be able to access authentication data cached by cred above, even in another process
	newCred, err := azidentity.NewInteractiveBrowserCredential(&azidentity.InteractiveBrowserCredentialOptions{
		AuthenticationRecord:           unmarshaled,
		DisableAutomaticAuthentication: true,
		TokenCachePersistenceOptions: &azidentity.TokenCachePersistenceOptions{
			Name: "myapp",
		},
	})
	if err != nil {
		// TODO: handle error
	}
	_ = newCred
}
Output:

Index

Examples

Constants

View Source
const EventAuthentication log.Event = "Authentication"

EventAuthentication entries contain information about authentication. This includes information like the names of environment variables used when obtaining credentials and the type of credential used.

Variables

View Source
var ErrAuthenticationRequired error = &credentialUnavailableError{"can't acquire a token without user interaction. Call Authenticate to interactively authenticate a user"}

ErrAuthenticationRequired indicates a credential's Authenticate method must be called to acquire a token because user interaction is required and the credential is configured not to automatically prompt the user.

Functions

func NewCredentialUnavailableError added in v1.3.0

func NewCredentialUnavailableError(message string) error

NewCredentialUnavailableError constructs an error indicating a credential can't attempt authentication because it lacks required data or state. When ChainedTokenCredential receives this error it will try its next credential, if any.

func ParseCertificates added in v0.12.0

func ParseCertificates(certData []byte, password []byte) ([]*x509.Certificate, crypto.PrivateKey, error)

ParseCertificates loads certificates and a private key, in PEM or PKCS12 format, for use with NewClientCertificateCredential. Pass nil for password if the private key isn't encrypted. This function can't decrypt keys in PEM format.

Types

type AuthenticationFailedError

type AuthenticationFailedError struct {
	// RawResponse is the HTTP response motivating the error, if available.
	RawResponse *http.Response
	// contains filtered or unexported fields
}

AuthenticationFailedError indicates an authentication request has failed.

func (*AuthenticationFailedError) Error

func (e *AuthenticationFailedError) Error() string

Error implements the error interface. Note that the message contents are not contractual and can change over time.

func (*AuthenticationFailedError) NonRetriable added in v0.2.0

func (*AuthenticationFailedError) NonRetriable()

NonRetriable indicates the request which provoked this error shouldn't be retried.

type AuthenticationRecord added in v1.8.0

type AuthenticationRecord struct {
	// Authority is the URL of the authority that issued the token.
	Authority string `json:"authority"`

	// ClientID is the ID of the application that authenticated the user.
	ClientID string `json:"clientId"`

	// HomeAccountID uniquely identifies the account.
	HomeAccountID string `json:"homeAccountId"`

	// TenantID identifies the tenant in which the user authenticated.
	TenantID string `json:"tenantId"`

	// Username is the user's preferred username.
	Username string `json:"username"`

	// Version of the AuthenticationRecord.
	Version string `json:"version"`
}

AuthenticationRecord is non-secret account information about an authenticated user that user credentials such as DeviceCodeCredential and InteractiveBrowserCredential can use to access previously cached authentication data. Call these credentials' Authenticate method to get an AuthenticationRecord for a user.

func (*AuthenticationRecord) UnmarshalJSON added in v1.8.0

func (a *AuthenticationRecord) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler for AuthenticationRecord

type AzureCLICredential

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

AzureCLICredential authenticates as the identity logged in to the Azure CLI.

func NewAzureCLICredential

func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredential, error)

NewAzureCLICredential constructs an AzureCLICredential. Pass nil to accept default options.

func (*AzureCLICredential) GetToken

GetToken requests a token from the Azure CLI. This credential doesn't cache tokens, so every call invokes the CLI. This method is called automatically by Azure SDK clients.

type AzureCLICredentialOptions

type AzureCLICredentialOptions struct {
	// AdditionallyAllowedTenants specifies tenants for which the credential may acquire tokens, in addition
	// to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the
	// logged in account can access.
	AdditionallyAllowedTenants []string

	// TenantID identifies the tenant the credential should authenticate in.
	// Defaults to the CLI's default tenant, which is typically the home tenant of the logged in user.
	TenantID string
	// contains filtered or unexported fields
}

AzureCLICredentialOptions contains optional parameters for AzureCLICredential.

type AzureDeveloperCLICredential added in v1.5.0

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

AzureDeveloperCLICredential authenticates as the identity logged in to the Azure Developer CLI.

func NewAzureDeveloperCLICredential added in v1.5.0

func NewAzureDeveloperCLICredential(options *AzureDeveloperCLICredentialOptions) (*AzureDeveloperCLICredential, error)

NewAzureDeveloperCLICredential constructs an AzureDeveloperCLICredential. Pass nil to accept default options.

func (*AzureDeveloperCLICredential) GetToken added in v1.5.0

GetToken requests a token from the Azure Developer CLI. This credential doesn't cache tokens, so every call invokes azd. This method is called automatically by Azure SDK clients.

type AzureDeveloperCLICredentialOptions added in v1.5.0

type AzureDeveloperCLICredentialOptions struct {
	// AdditionallyAllowedTenants specifies tenants for which the credential may acquire tokens, in addition
	// to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the
	// logged in account can access.
	AdditionallyAllowedTenants []string

	// TenantID identifies the tenant the credential should authenticate in. Defaults to the azd environment,
	// which is the tenant of the selected Azure subscription.
	TenantID string
	// contains filtered or unexported fields
}

AzureDeveloperCLICredentialOptions contains optional parameters for AzureDeveloperCLICredential.

type ChainedTokenCredential

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

ChainedTokenCredential links together multiple credentials and tries them sequentially when authenticating. By default, it tries all the credentials until one authenticates, after which it always uses that credential.

func NewChainedTokenCredential

func NewChainedTokenCredential(sources []azcore.TokenCredential, options *ChainedTokenCredentialOptions) (*ChainedTokenCredential, error)

NewChainedTokenCredential creates a ChainedTokenCredential. Pass nil for options to accept defaults.

Example (ManagedIdentityTimeout)

This example demonstrates a small wrapper that sets a deadline for authentication and signals ChainedTokenCredential to try another credential when managed identity authentication times out, as it would for example in a local development environment.

//go:build go1.18
// +build go1.18

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package main

import (
	"context"
	"errors"
	"time"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

// timeoutWrapper signals ChainedTokenCredential to try another credential when managed identity times out
type timeoutWrapper struct {
	cred    *azidentity.ManagedIdentityCredential
	timeout time.Duration
}

// GetToken implements the azcore.TokenCredential interface
func (w *timeoutWrapper) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
	var tk azcore.AccessToken
	var err error
	if w.timeout > 0 {
		c, cancel := context.WithTimeout(ctx, w.timeout)
		defer cancel()
		tk, err = w.cred.GetToken(c, opts)
		if ce := c.Err(); errors.Is(ce, context.DeadlineExceeded) {
			// The Context reached its deadline, probably because no managed identity is available.
			// A credential unavailable error signals the chain to try its next credential, if any.
			err = azidentity.NewCredentialUnavailableError("managed identity timed out")
		} else {
			// some managed identity implementation is available, so don't apply the timeout to future calls
			w.timeout = 0
		}
	} else {
		tk, err = w.cred.GetToken(ctx, opts)
	}
	return tk, err
}

// This example demonstrates a small wrapper that sets a deadline for authentication and signals
// [ChainedTokenCredential] to try another credential when managed identity authentication times
// out, as it would for example in a local development environment.
func main() {
	mic, err := azidentity.NewManagedIdentityCredential(nil)
	if err != nil {
		// TODO: handle error
	}
	azCLI, err := azidentity.NewAzureCLICredential(nil)
	if err != nil {
		// TODO: handle error
	}
	creds := []azcore.TokenCredential{
		&timeoutWrapper{mic, time.Second},
		azCLI,
	}
	chain, err := azidentity.NewChainedTokenCredential(creds, nil)
	if err != nil {
		// TODO: handle error
	}
	// TODO: construct a client with the credential chain
	_ = chain
}
Output:

func (*ChainedTokenCredential) GetToken

GetToken calls GetToken on the chained credentials in turn, stopping when one returns a token. This method is called automatically by Azure SDK clients.

type ChainedTokenCredentialOptions added in v0.12.0

type ChainedTokenCredentialOptions struct {
	// RetrySources configures how the credential uses its sources. When true, the credential always attempts to
	// authenticate through each source in turn, stopping when one succeeds. When false, the credential authenticates
	// only through this first successful source--it never again tries the sources which failed.
	RetrySources bool
}

ChainedTokenCredentialOptions contains optional parameters for ChainedTokenCredential.

type ClientAssertionCredential added in v1.2.0

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

ClientAssertionCredential authenticates an application with assertions provided by a callback function. This credential is for advanced scenarios. ClientCertificateCredential has a more convenient API for the most common assertion scenario, authenticating a service principal with a certificate. See Azure AD documentation for details of the assertion format.

func NewClientAssertionCredential added in v1.2.0

func NewClientAssertionCredential(tenantID, clientID string, getAssertion func(context.Context) (string, error), options *ClientAssertionCredentialOptions) (*ClientAssertionCredential, error)

NewClientAssertionCredential constructs a ClientAssertionCredential. The getAssertion function must be thread safe. Pass nil for options to accept defaults.

func (*ClientAssertionCredential) GetToken added in v1.2.0

GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.

type ClientAssertionCredentialOptions added in v1.2.0

type ClientAssertionCredentialOptions struct {
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
	// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
	// application is registered.
	AdditionallyAllowedTenants []string

	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool

	// TokenCachePersistenceOptions enables persistent token caching when not nil.
	TokenCachePersistenceOptions *TokenCachePersistenceOptions
}

ClientAssertionCredentialOptions contains optional parameters for ClientAssertionCredential.

type ClientCertificateCredential

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

ClientCertificateCredential authenticates a service principal with a certificate.

func NewClientCertificateCredential

func NewClientCertificateCredential(tenantID string, clientID string, certs []*x509.Certificate, key crypto.PrivateKey, options *ClientCertificateCredentialOptions) (*ClientCertificateCredential, error)

NewClientCertificateCredential constructs a ClientCertificateCredential. Pass nil for options to accept defaults.

Example
data, err := os.ReadFile(certPath)
handleError(err)

// NewClientCertificateCredential requires at least one *x509.Certificate, and a crypto.PrivateKey.
// ParseCertificates returns these given certificate data in PEM or PKCS12 format. It handles common scenarios
// but has limitations, for example it doesn't load PEM encrypted private keys.
certs, key, err := azidentity.ParseCertificates(data, nil)
handleError(err)

cred, err = azidentity.NewClientCertificateCredential(tenantID, clientID, certs, key, nil)
handleError(err)
Output:

func (*ClientCertificateCredential) GetToken

GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.

type ClientCertificateCredentialOptions added in v0.4.0

type ClientCertificateCredentialOptions struct {
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
	// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
	// application is registered.
	AdditionallyAllowedTenants []string

	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool

	// SendCertificateChain controls whether the credential sends the public certificate chain in the x5c
	// header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication.
	// Defaults to False.
	SendCertificateChain bool

	// TokenCachePersistenceOptions enables persistent token caching when not nil.
	TokenCachePersistenceOptions *TokenCachePersistenceOptions
}

ClientCertificateCredentialOptions contains optional parameters for ClientCertificateCredential.

type ClientID added in v0.9.2

type ClientID string

ClientID is the client ID of a user-assigned managed identity.

func (ClientID) String added in v0.12.0

func (c ClientID) String() string

String returns the string value of the ID.

type ClientSecretCredential

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

ClientSecretCredential authenticates an application with a client secret.

func NewClientSecretCredential

func NewClientSecretCredential(tenantID string, clientID string, clientSecret string, options *ClientSecretCredentialOptions) (*ClientSecretCredential, error)

NewClientSecretCredential constructs a ClientSecretCredential. Pass nil for options to accept defaults.

func (*ClientSecretCredential) GetToken

GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.

type ClientSecretCredentialOptions added in v0.4.0

type ClientSecretCredentialOptions struct {
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
	// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
	// application is registered.
	AdditionallyAllowedTenants []string

	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool

	// TokenCachePersistenceOptions enables persistent token caching when not nil.
	TokenCachePersistenceOptions *TokenCachePersistenceOptions
}

ClientSecretCredentialOptions contains optional parameters for ClientSecretCredential.

type DefaultAzureCredential added in v0.12.0

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

DefaultAzureCredential is a default credential chain for applications that will deploy to Azure. It combines credentials suitable for deployment with credentials suitable for local development. It attempts to authenticate with each of these credential types, in the following order, stopping when one provides a token:

Consult the documentation for these credential types for more information on how they authenticate. Once a credential has successfully authenticated, DefaultAzureCredential will use that credential for every subsequent authentication.

func NewDefaultAzureCredential

func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*DefaultAzureCredential, error)

NewDefaultAzureCredential creates a DefaultAzureCredential. Pass nil for options to accept defaults.

func (*DefaultAzureCredential) GetToken added in v0.12.0

GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.

type DefaultAzureCredentialOptions

type DefaultAzureCredentialOptions struct {
	// ClientOptions has additional options for credentials that use an Azure SDK HTTP pipeline. These options don't apply
	// to credential types that authenticate via external tools such as the Azure CLI.
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. Add
	// the wildcard value "*" to allow the credential to acquire tokens for any tenant. This value can also be
	// set as a semicolon delimited list of tenants in the environment variable AZURE_ADDITIONALLY_ALLOWED_TENANTS.
	AdditionallyAllowedTenants []string
	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool
	// TenantID sets the default tenant for authentication via the Azure CLI and workload identity.
	TenantID string
}

DefaultAzureCredentialOptions contains optional parameters for DefaultAzureCredential. These options may not apply to all credentials in the chain.

type DeviceCodeCredential

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

DeviceCodeCredential acquires tokens for a user via the device code flow, which has the user browse to an Azure Active Directory URL, enter a code, and authenticate. It's useful for authenticating a user in an environment without a web browser, such as an SSH session. If a web browser is available, InteractiveBrowserCredential is more convenient because it automatically opens a browser to the login page.

func NewDeviceCodeCredential

func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeCredential, error)

NewDeviceCodeCredential creates a DeviceCodeCredential. Pass nil to accept default options.

func (*DeviceCodeCredential) Authenticate added in v1.8.0

Authenticate a user via the device code flow. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord.

func (*DeviceCodeCredential) GetToken

GetToken requests an access token from Azure Active Directory. It will begin the device code flow and poll until the user completes authentication. This method is called automatically by Azure SDK clients.

type DeviceCodeCredentialOptions added in v0.2.2

type DeviceCodeCredentialOptions struct {
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire
	// tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant.
	AdditionallyAllowedTenants []string

	// AuthenticationRecord returned by a call to a credential's Authenticate method. Set this option
	// to enable the credential to use data from a previous authentication.
	AuthenticationRecord AuthenticationRecord

	// ClientID is the ID of the application users will authenticate to.
	// Defaults to the ID of an Azure development application.
	ClientID string

	// DisableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate.
	// When this option is true, [DeviceCodeCredential.GetToken] will return [ErrAuthenticationRequired] when user
	// interaction is necessary to acquire a token.
	DisableAutomaticAuthentication bool

	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool

	// TenantID is the Azure Active Directory tenant the credential authenticates in. Defaults to the
	// "organizations" tenant, which can authenticate work and school accounts. Required for single-tenant
	// applications.
	TenantID string

	// TokenCachePersistenceOptions enables persistent token caching when not nil.
	TokenCachePersistenceOptions *TokenCachePersistenceOptions

	// UserPrompt controls how the credential presents authentication instructions. The credential calls
	// this function with authentication details when it receives a device code. By default, the credential
	// prints these details to stdout.
	UserPrompt func(context.Context, DeviceCodeMessage) error
}

DeviceCodeCredentialOptions contains optional parameters for DeviceCodeCredential.

type DeviceCodeMessage added in v0.3.0

type DeviceCodeMessage struct {
	// UserCode is the user code returned by the service.
	UserCode string `json:"user_code"`
	// VerificationURL is the URL at which the user must authenticate.
	VerificationURL string `json:"verification_uri"`
	// Message is user instruction from Azure Active Directory.
	Message string `json:"message"`
}

DeviceCodeMessage contains the information a user needs to complete authentication.

type EnvironmentCredential added in v0.2.1

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

EnvironmentCredential authenticates a service principal with a secret or certificate, or a user with a password, depending on environment variable configuration. It reads configuration from these variables, in the following order:

Service principal with client secret

AZURE_TENANT_ID: ID of the service principal's tenant. Also called its "directory" ID.

AZURE_CLIENT_ID: the service principal's client ID

AZURE_CLIENT_SECRET: one of the service principal's client secrets

Service principal with certificate

AZURE_TENANT_ID: ID of the service principal's tenant. Also called its "directory" ID.

AZURE_CLIENT_ID: the service principal's client ID

AZURE_CLIENT_CERTIFICATE_PATH: path to a PEM or PKCS12 certificate file including the private key.

AZURE_CLIENT_CERTIFICATE_PASSWORD: (optional) password for the certificate file.

User with username and password

AZURE_TENANT_ID: (optional) tenant to authenticate in. Defaults to "organizations".

AZURE_CLIENT_ID: client ID of the application the user will authenticate to

AZURE_USERNAME: a username (usually an email address)

AZURE_PASSWORD: the user's password

Configuration for multitenant applications

To enable multitenant authentication, set AZURE_ADDITIONALLY_ALLOWED_TENANTS with a semicolon delimited list of tenants the credential may request tokens from in addition to the tenant specified by AZURE_TENANT_ID. Set AZURE_ADDITIONALLY_ALLOWED_TENANTS to "*" to enable the credential to request a token from any tenant.

func NewEnvironmentCredential

func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*EnvironmentCredential, error)

NewEnvironmentCredential creates an EnvironmentCredential. Pass nil to accept default options.

func (*EnvironmentCredential) GetToken added in v0.2.1

GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.

type EnvironmentCredentialOptions added in v0.4.0

type EnvironmentCredentialOptions struct {
	azcore.ClientOptions

	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool
	// contains filtered or unexported fields
}

EnvironmentCredentialOptions contains optional parameters for EnvironmentCredential

type InteractiveBrowserCredential added in v0.2.1

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

InteractiveBrowserCredential opens a browser to interactively authenticate a user.

func NewInteractiveBrowserCredential added in v0.2.1

func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOptions) (*InteractiveBrowserCredential, error)

NewInteractiveBrowserCredential constructs a new InteractiveBrowserCredential. Pass nil to accept default options.

func (*InteractiveBrowserCredential) Authenticate added in v1.8.0

Authenticate a user via the default browser. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord.

func (*InteractiveBrowserCredential) GetToken added in v0.2.1

GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.

type InteractiveBrowserCredentialOptions added in v0.2.1

type InteractiveBrowserCredentialOptions struct {
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire
	// tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant.
	AdditionallyAllowedTenants []string

	// AuthenticationRecord returned by a call to a credential's Authenticate method. Set this option
	// to enable the credential to use data from a previous authentication.
	AuthenticationRecord AuthenticationRecord

	// ClientID is the ID of the application users will authenticate to.
	// Defaults to the ID of an Azure development application.
	ClientID string

	// DisableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate.
	// When this option is true, [InteractiveBrowserCredential.GetToken] will return [ErrAuthenticationRequired] when
	// user interaction is necessary to acquire a token.
	DisableAutomaticAuthentication bool

	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool

	// LoginHint pre-populates the account prompt with a username. Users may choose to authenticate a different account.
	LoginHint string

	// RedirectURL is the URL Azure Active Directory will redirect to with the access token. This is required
	// only when setting ClientID, and must match a redirect URI in the application's registration.
	// Applications which have registered "http://localhost" as a redirect URI need not set this option.
	RedirectURL string

	// TenantID is the Azure Active Directory tenant the credential authenticates in. Defaults to the
	// "organizations" tenant, which can authenticate work and school accounts.
	TenantID string

	// TokenCachePersistenceOptions enables persistent token caching when not nil.
	TokenCachePersistenceOptions *TokenCachePersistenceOptions
}

InteractiveBrowserCredentialOptions contains optional parameters for InteractiveBrowserCredential.

type ManagedIDKind added in v0.12.0

type ManagedIDKind interface {
	fmt.Stringer
	// contains filtered or unexported methods
}

ManagedIDKind identifies the ID of a managed identity as either a client or resource ID

type ManagedIdentityCredential

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

ManagedIdentityCredential authenticates an Azure managed identity in any hosting environment supporting managed identities. This credential authenticates a system-assigned identity by default. Use ManagedIdentityCredentialOptions.ID to specify a user-assigned identity. See Azure Active Directory documentation for more information about managed identities: https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview

func NewManagedIdentityCredential

func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*ManagedIdentityCredential, error)

NewManagedIdentityCredential creates a ManagedIdentityCredential. Pass nil to accept default options.

Example (UserAssigned)
// select a user assigned identity with its client ID...
clientID := azidentity.ClientID("abcd1234-...")
opts := azidentity.ManagedIdentityCredentialOptions{ID: clientID}
cred, err = azidentity.NewManagedIdentityCredential(&opts)
handleError(err)

// ...or its resource ID
resourceID := azidentity.ResourceID("/subscriptions/...")
opts = azidentity.ManagedIdentityCredentialOptions{ID: resourceID}
cred, err = azidentity.NewManagedIdentityCredential(&opts)
handleError(err)
Output:

func (*ManagedIdentityCredential) GetToken

GetToken requests an access token from the hosting environment. This method is called automatically by Azure SDK clients.

type ManagedIdentityCredentialOptions

type ManagedIdentityCredentialOptions struct {
	azcore.ClientOptions

	// ID is the ID of a managed identity the credential should authenticate. Set this field to use a specific identity
	// instead of the hosting environment's default. The value may be the identity's client ID or resource ID, but note that
	// some platforms don't accept resource IDs.
	ID ManagedIDKind
}

ManagedIdentityCredentialOptions contains optional parameters for ManagedIdentityCredential.

type OnBehalfOfCredential added in v1.3.0

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

OnBehalfOfCredential authenticates a service principal via the on-behalf-of flow. This is typically used by middle-tier services that authorize requests to other services with a delegated user identity. Because this is not an interactive authentication flow, an application using it must have admin consent for any delegated permissions before requesting tokens for them. See Azure Active Directory documentation for more details.

func NewOnBehalfOfCredentialWithCertificate added in v1.3.0

func NewOnBehalfOfCredentialWithCertificate(tenantID, clientID, userAssertion string, certs []*x509.Certificate, key crypto.PrivateKey, options *OnBehalfOfCredentialOptions) (*OnBehalfOfCredential, error)

NewOnBehalfOfCredentialWithCertificate constructs an OnBehalfOfCredential that authenticates with a certificate. See ParseCertificates for help loading a certificate.

Example
data, err := os.ReadFile(certPath)
if err != nil {
	// TODO: handle error
}

// NewOnBehalfOfCredentialFromCertificate requires at least one *x509.Certificate, and a crypto.PrivateKey.
// ParseCertificates returns these given certificate data in PEM or PKCS12 format. It handles common
// scenarios but has limitations, for example it doesn't load PEM encrypted private keys.
certs, key, err := azidentity.ParseCertificates(data, nil)
if err != nil {
	// TODO: handle error
}

cred, err = azidentity.NewClientCertificateCredential(tenantID, clientID, certs, key, nil)
if err != nil {
	// TODO: handle error
}
Output:

func NewOnBehalfOfCredentialWithSecret added in v1.3.0

func NewOnBehalfOfCredentialWithSecret(tenantID, clientID, userAssertion, clientSecret string, options *OnBehalfOfCredentialOptions) (*OnBehalfOfCredential, error)

NewOnBehalfOfCredentialWithSecret constructs an OnBehalfOfCredential that authenticates with a client secret.

func (*OnBehalfOfCredential) GetToken added in v1.3.0

GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.

type OnBehalfOfCredentialOptions added in v1.3.0

type OnBehalfOfCredentialOptions struct {
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
	// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
	// application is registered.
	AdditionallyAllowedTenants []string

	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool

	// SendCertificateChain applies only when the credential is configured to authenticate with a certificate.
	// This setting controls whether the credential sends the public certificate chain in the x5c header of each
	// token request's JWT. This is required for, and only used in, Subject Name/Issuer (SNI) authentication.
	SendCertificateChain bool
}

OnBehalfOfCredentialOptions contains optional parameters for OnBehalfOfCredential

type ResourceID added in v0.9.2

type ResourceID string

ResourceID is the resource ID of a user-assigned managed identity.

func (ResourceID) String added in v0.12.0

func (r ResourceID) String() string

String returns the string value of the ID.

type TokenCachePersistenceOptions

type TokenCachePersistenceOptions = internal.TokenCachePersistenceOptions

TokenCachePersistenceOptions contains options for persistent token caching

type UsernamePasswordCredential

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

UsernamePasswordCredential authenticates a user with a password. Microsoft doesn't recommend this kind of authentication, because it's less secure than other authentication flows. This credential is not interactive, so it isn't compatible with any form of multi-factor authentication, and the application must already have user or admin consent. This credential can only authenticate work and school accounts; it can't authenticate Microsoft accounts.

func NewUsernamePasswordCredential

func NewUsernamePasswordCredential(tenantID string, clientID string, username string, password string, options *UsernamePasswordCredentialOptions) (*UsernamePasswordCredential, error)

NewUsernamePasswordCredential creates a UsernamePasswordCredential. clientID is the ID of the application the user will authenticate to. Pass nil for options to accept defaults.

func (*UsernamePasswordCredential) Authenticate added in v1.8.0

Authenticate the user. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord.

func (*UsernamePasswordCredential) GetToken

GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.

type UsernamePasswordCredentialOptions added in v0.4.0

type UsernamePasswordCredentialOptions struct {
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
	// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
	// application is registered.
	AdditionallyAllowedTenants []string

	// AuthenticationRecord returned by a call to a credential's Authenticate method. Set this option
	// to enable the credential to use data from a previous authentication.
	AuthenticationRecord AuthenticationRecord

	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool

	// TokenCachePersistenceOptions enables persistent token caching when not nil.
	TokenCachePersistenceOptions *TokenCachePersistenceOptions
}

UsernamePasswordCredentialOptions contains optional parameters for UsernamePasswordCredential.

type WorkloadIdentityCredential added in v1.3.0

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

WorkloadIdentityCredential supports Azure workload identity on Kubernetes. See Azure Kubernetes Service documentation for more information.

func NewWorkloadIdentityCredential added in v1.3.0

func NewWorkloadIdentityCredential(options *WorkloadIdentityCredentialOptions) (*WorkloadIdentityCredential, error)

NewWorkloadIdentityCredential constructs a WorkloadIdentityCredential. Service principal configuration is read from environment variables as set by the Azure workload identity webhook. Set options to override those values.

func (*WorkloadIdentityCredential) GetToken added in v1.3.0

GetToken requests an access token from Azure Active Directory. Azure SDK clients call this method automatically.

type WorkloadIdentityCredentialOptions added in v1.3.0

type WorkloadIdentityCredentialOptions struct {
	azcore.ClientOptions

	// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
	// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
	// application is registered.
	AdditionallyAllowedTenants []string
	// ClientID of the service principal. Defaults to the value of the environment variable AZURE_CLIENT_ID.
	ClientID string
	// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
	// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
	// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
	// the application responsible for ensuring the configured authority is valid and trustworthy.
	DisableInstanceDiscovery bool
	// TenantID of the service principal. Defaults to the value of the environment variable AZURE_TENANT_ID.
	TenantID string
	// TokenFilePath is the path of a file containing a Kubernetes service account token. Defaults to the value of the
	// environment variable AZURE_FEDERATED_TOKEN_FILE.
	TokenFilePath string
}

WorkloadIdentityCredentialOptions contains optional parameters for WorkloadIdentityCredential.

Directories

Path Synopsis
cache module

Jump to

Keyboard shortcuts

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