azidentity

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2021 License: MIT Imports: 35 Imported by: 1,796

README

Azure Identity Client Module for Go

PkgGoDev Build Status Code Coverage

The azidentity module provides a set of credential types for use with Azure SDK clients that support Azure Active Directory (AAD) token authentication.

Source code | Azure Active Directory documentation

Getting started

Install the package

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 it is typical for developers to use their own accounts for authenticating 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.

Azure CLI Account Sign In

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.

Azure CLI Account Device Code Sign In

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 AAD access token. See Credential Types below for a list of this module's credential types.

DefaultAzureCredential

The DefaultAzureCredential is appropriate for most scenarios where the application is ultimately intended to run in Azure Cloud. This is because DefaultAzureCredential combines credentials commonly used to authenticate when deployed, with credentials used to authenticate in a development environment.

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.

The DefaultAzureCredential will attempt to authenticate via the following mechanisms in order.

DefaultAzureCredential authentication flow

  • Environment - The DefaultAzureCredential will read account information specified via environment variables and use it to authenticate.
  • Managed Identity - If the application is deployed to an Azure host with Managed Identity enabled, the DefaultAzureCredential will authenticate with that account.
  • Azure CLI - If the developer has authenticated an account via the Azure CLI az login command, the DefaultAzureCredential will authenticate with that account.

Examples

You can find more examples of using various credentials in Azure Identity Examples Wiki page.

Authenticating with DefaultAzureCredential

This example demonstrates authenticating the ResourcesClient from the armresources module using DefaultAzureCredential.

// The default credential checks environment variables for configuration.
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
  // handle error
}

// Azure SDK Azure Resource Management clients accept the credential as a parameter
client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil), "<subscription ID>")

See more how to configure the DefaultAzureCredential on your workstation or Azure in Configure DefaultAzureCredential.

Authenticating a user assigned managed identity with DefaultAzureCredential

This example demonstrates authenticating the ResourcesClient from the armresources module using the DefaultAzureCredential, deployed to an Azure resource with a user assigned managed identity configured.

See more about how to configure a user assigned managed identity for an Azure resource in Enable managed identity for Azure resources.

// The default credential will use the user assigned managed identity with the specified client ID.
// The client_ID for the user assigned is set through an environment variable.
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
  // handle error
}

// Azure SDK Azure Resource Management clients accept the credential as a parameter
client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil), "<subscription ID>")

Managed Identity Support

The Managed identity authentication is supported via either the DefaultAzureCredential or the ManagedIdentityCredential directly for the following Azure Services:

Examples
Authenticating in Azure with Managed Identity

This examples demonstrates authenticating the ResourcesClient from the armresources module using ManagedIdentityCredential in a virtual machine, app service, function app, cloud shell, or AKS environment on Azure, with system assigned, or user assigned managed identity enabled.

See more about how to configure your Azure resource for managed identity in Enable managed identity for Azure resources

// Authenticate with a User Assigned Managed Identity.
cred, err := azidentity.NewManagedIdentityCredential("<USER ASSIGNED MANAGED IDENTITY CLIENT ID>", nil) // specify a client_ID for the user assigned identity
if err != nil {
  // handle error
}

// Azure SDK Azure Resource Management clients accept the credential as a parameter
client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil), "<subscription ID>")
// Authenticate with a System Assigned Managed Identity.
cred, err := azidentity.NewManagedIdentityCredential("", nil) // do not specify a client_ID to use the system assigned identity
if err != nil {
  // handle error
}

// Azure SDK Azure Resource Management clients accept the credential as a parameter
client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil), "<subscription ID>")

Credential Types

Authenticating Azure Hosted Applications
credential usage configuration example
DefaultAzureCredential simplified authentication experience to get started developing applications for the Azure cloud configuration example
ChainedTokenCredential define custom authentication flows composing multiple credentials example
EnvironmentCredential authenticate a service principal or user configured by environment variables
ManagedIdentityCredential authenticate the managed identity of an Azure resource configuration example
Authenticating Service Principals
credential usage configuration example reference
ClientSecretCredential authenticate a service principal using a secret configuration example Service principal authentication
CertificateCredential authenticate a service principal using a certificate configuration example Service principal authentication
Authenticating Users
credential usage configuration example reference
InteractiveBrowserCredential interactively authenticate a user with the default web browser configuration example OAuth2 authentication code
DeviceCodeCredential interactively authenticate a user on a device with limited UI configuration example Device code authentication
UsernamePasswordCredential authenticate a user with a username and password example Username + password authentication
AuthorizationCodeCredential authenticate a user with a previously obtained authorization code as part of an Oauth 2 flow configuration OAuth2 authentication code
Authenticating via Development Tools
credential usage configuration example reference
AzureCLICredential authenticate as the user signed in to the Azure CLI configuration example Azure CLI authentication

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 PEM-encoded certificate file including private key (without password protection)
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 CredentialUnavailableError when they're unable to attempt authentication because they lack required data or state. For example, NewEnvironmentCredential will return an error when its configuration is incomplete.

Credentials return AuthenticationFailedError when they fail to authenticate. Call Error() on AuthenticationFailedError to see why authentication failed. When returned by DefaultAzureCredential or ChainedTokenCredential, the message collects error messages from each credential in the chain.

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 turn on logging set AZURE_SDK_GO_LOGGING to all. If you only want to include logs for azidentity, you must create you own logger and set the log classification as EventCredential. Credentials log basic information only, including GetToken success or failure and errors. These log entries do not contain authentication secrets but may contain sensitive information.

To obtain more detailed logging, including request/response bodies and header values, make sure to leave the logger as default or enable the LogRequest and/or LogResponse classifications. A logger that only includes credential logs can be like the following:

import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
// Set log to output to the console
azlog.SetListener(func(cls LogClassification, s string) {
		fmt.Println(s) // printing log out to the console
  })

// Include only azidentity credential logs
azlog.SetClassifications(azidentity.EventCredential)

CAUTION: logs from credentials contain sensitive information. These logs must be protected to avoid compromising account security.

Next steps

The Go client libraries listed here support authenticating with TokenCredential and the Azure Identity library. You can learn more about their use, and find additional documentation on use of these client libraries along samples with can be found in the links mentioned here.

Provide Feedback

If you encounter bugs or have suggestions, please open an issue and assign the Azure.Identity label.

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

Package azidentity implements a set of credential types for use with Azure SDK clients that support Azure Active Directory (AAD) token authentication.

The following credential types are included in this module:

  • AuthorizationCodeCredential
  • AzureCLICredential
  • ChainedTokenCredential
  • ClientCertificateCredential
  • ClientSecretCredential
  • DefaultAzureCredential
  • DeviceCodeCredential
  • EnvironmentCredential
  • InteractiveBrowserCredential
  • ManagedIdentityCredential
  • UsernamePasswordCredential

By default, the recommendation is that users call NewDefaultAzureCredential() which will provide a default ChainedTokenCredential configuration composed of:

  • EnvironmentCredential
  • ManagedIdentityCredential
  • AzureCLICredential

Configuration options can be used to exclude any of the previous credentials from the DefaultAzureCredential implementation.

Example call to NewDefaultAzureCredential():

cred, err := NewDefaultAzureCredential(nil) // pass in nil to get default behavior for this credential
if err != nil {
	// process error
}
// pass credential in to an Azure SDK client

Example call to NewDefaultAzureCredential() with options set:

// these options will make sure the AzureCLICredential will not be added to the credential chain
cred, err := NewDefaultAzureCredential(&DefaultAzureCredentialOptions{ExcludeAzureCLICredential: true})
if err != nil {
	// process error
}
// pass credential in to an Azure SDK client

Additional configuration of each credential can be done through each credential's options type. These options can also be used to modify the default pipeline for each credential.

Example pattern for modifying credential options:

cred, err := azidentity.NewClientCertificateCredential("<tenant ID>", "<client ID>", "<certificate path>", &ClientCertificateCredentialOptions{Password: "<certificate password>"})
if err != nil {
	// process error
}

CREDENTIAL AUTHORITY HOSTS

The default authority host for all credentials, except for ManagedIdentityCredential, is the AzurePublicCloud host. This value can be changed through the credential options or by specifying a different value in an environment variable called AZURE_AUTHORITY_HOST. NOTE: An alternate value for authority host explicitly set through the code will take precedence over the AZURE_AUTHORITY_HOST environment variable.

Example of setting an alternate Azure authority host through code:

cred, err := azidentity.NewClientSecretCredential("<tenant ID>", "<client ID>", "<client secret>", &ClientSecretCredentialOptions{AuthorityHost: azidentity.AzureChina})
if err != nil {
	// process error
}
// pass credential in to an Azure SDK client

Example of setting an alternate authority host value in the AZURE_AUTHORITY_HOST environment variable (in Powershell):

$env:AZURE_AUTHORITY_HOST="https://contoso.com/auth/"

ERROR HANDLING

The credential types in azidentity will return one of the following error types, unless there was some other unexpected failure:

  • CredentialUnavailableError: This error signals that an essential component for using the credential is missing or that the credential is being instantiated in an environment that is incompatible with its functionality. These will generally be returned at credential creation after calling the constructor.
  • AuthenticationFailedError: This error typically signals that a request has been made to the service and that authentication failed at the service level.

Index

Examples

Constants

View Source
const EventCredential log.Event = "Credential"

EventCredential 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

This section is empty.

Functions

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 for use with NewClientCertificateCredential. certData: certificate data encoded in PEM or PKCS12 format, including the certificate's private key. password: the password required to decrypt the private key. Pass nil if the key is not encrypted. This function can't decrypt keys in PEM format.

Types

type AuthenticationFailedError

type AuthenticationFailedError interface {
	azcore.HTTPResponse
	errorinfo.NonRetriable
	AuthenticationFailed()
}

AuthenticationFailedError indicates an authentication request has failed.

type AuthorityHost added in v0.12.0

type AuthorityHost string

AuthorityHost is the base URL for Azure Active Directory

const (
	// AzureChina is a global constant to use in order to access the Azure China cloud.
	AzureChina AuthorityHost = "https://login.chinacloudapi.cn/"
	// AzureGovernment is a global constant to use in order to access the Azure Government cloud.
	AzureGovernment AuthorityHost = "https://login.microsoftonline.us/"
	// AzurePublicCloud is a global constant to use in order to access the Azure public cloud.
	AzurePublicCloud AuthorityHost = "https://login.microsoftonline.com/"
)

type AuthorizationCodeCredential added in v0.2.2

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

AuthorizationCodeCredential enables authentication to Azure Active Directory using an authorization code that was obtained through the authorization code flow, described in more detail in the Azure Active Directory documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow.

func NewAuthorizationCodeCredential added in v0.2.2

func NewAuthorizationCodeCredential(tenantID string, clientID string, authCode string, redirectURL string, options *AuthorizationCodeCredentialOptions) (*AuthorizationCodeCredential, error)

NewAuthorizationCodeCredential constructs a new AuthorizationCodeCredential with the details needed to authenticate against Azure Active Directory with an authorization code. tenantID: The Azure Active Directory tenant (directory) ID of the service principal. clientID: The client (application) ID of the service principal. authCode: The authorization code received from the authorization code flow. The authorization code must not have been used to obtain another token. redirectURL: The redirect URL that was used to request the authorization code. Must be the same URL that is configured for the App Registration. options: Manage the configuration of the requests sent to Azure Active Directory, they can also include a client secret for web app authentication.

func (*AuthorizationCodeCredential) GetToken added in v0.2.2

GetToken obtains a token from Azure Active Directory, using the specified authorization code to authenticate. ctx: Context used to control the request lifetime. opts: TokenRequestOptions contains the list of scopes for which the token will have access. Returns an AccessToken which can be used to authenticate service client calls.

type AuthorizationCodeCredentialOptions added in v0.2.2

type AuthorizationCodeCredentialOptions struct {
	azcore.ClientOptions

	// Gets the client secret that was generated for the App Registration used to authenticate the client.
	ClientSecret string
	// The host of the Azure Active Directory authority. The default is AzurePublicCloud.
	// Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable.
	AuthorityHost AuthorityHost
}

AuthorizationCodeCredentialOptions contain optional parameters that can be used to configure the AuthorizationCodeCredential. All zero-value fields will be initialized with their default values.

type AzureCLICredential

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

AzureCLICredential enables authentication to Azure Active Directory using the Azure CLI command "az account get-access-token".

func NewAzureCLICredential

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

NewAzureCLICredential constructs a new AzureCLICredential with the details needed to authenticate against Azure Active Directory options: configure the management of the requests sent to Azure Active Directory.

func (*AzureCLICredential) GetToken

GetToken obtains a token from Azure Active Directory, using the Azure CLI command to authenticate. ctx: Context used to control the request lifetime. opts: TokenRequestOptions contains the list of scopes for which the token will have access. Returns an AccessToken which can be used to authenticate service client calls.

type AzureCLICredentialOptions

type AzureCLICredentialOptions struct {

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

AzureCLICredentialOptions contains options used to configure the AzureCLICredential All zero-value fields will be initialized with their default values.

type ChainedTokenCredential

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

ChainedTokenCredential provides a TokenCredential implementation that chains multiple TokenCredential sources to be tried in order and returns the token from the first successful call to GetToken().

func NewChainedTokenCredential

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

NewChainedTokenCredential creates an instance of ChainedTokenCredential with the specified TokenCredential sources.

func (*ChainedTokenCredential) GetToken

GetToken sequentially calls TokenCredential.GetToken on all the specified sources, returning the token from the first successful call to GetToken().

type ChainedTokenCredentialOptions added in v0.12.0

type ChainedTokenCredentialOptions struct {
}

ChainedTokenCredentialOptions contains optional parameters for ChainedTokenCredential

type ClientCertificateCredential

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

ClientCertificateCredential enables authentication of a service principal to Azure Active Directory using a certificate that is assigned to its App Registration. More information on how to configure certificate authentication can be found here: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad

func NewClientCertificateCredential

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

NewClientCertificateCredential creates an instance of ClientCertificateCredential with the details needed to authenticate against Azure Active Directory with the specified certificate. tenantID: The Azure Active Directory tenant (directory) ID of the service principal. clientID: The client (application) ID of the service principal. certs: one or more certificates, for example as returned by ParseCertificates() key: the signing certificate's private key, for example as returned by ParseCertificates() options: ClientCertificateCredentialOptions that can be used to provide additional configurations for the credential, such as the certificate password.

Example
package main

import (
	"log"
	"os"

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

const (
	certPath = "testdata/certificate.pem"
	clientID = "fake-client-id"
	tenantID = "fake-tenant"
)

var cred *azidentity.ClientCertificateCredential

func handleError(err error) {
	if err != nil {
		log.Panicf("example failed: %v", err)
	}
}

func main() {
	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 obtains a token from Azure Active Directory, using the provided certificate. ctx: Context controlling the request lifetime. opts: details of the authentication request. Returns an AccessToken which can be used to authenticate service client calls.

type ClientCertificateCredentialOptions added in v0.4.0

type ClientCertificateCredentialOptions struct {
	azcore.ClientOptions

	// Set to true to include x5c header in client claims when acquiring a token to enable
	// SubjectName and Issuer based authentication for ClientCertificateCredential.
	SendCertificateChain bool
	// The host of the Azure Active Directory authority. The default is AzurePublicCloud.
	// Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable.
	AuthorityHost AuthorityHost
}

ClientCertificateCredentialOptions contain optional parameters that can be used when configuring a ClientCertificateCredential. All zero-value fields will be initialized with their default values.

type ClientID added in v0.9.2

type ClientID string

ClientID is an identity's client ID. Use it with ManagedIdentityCredentialOptions, for example: ManagedIdentityCredentialOptions{ID: ClientID("7cf7db0d-...")}

func (ClientID) String added in v0.12.0

func (c ClientID) String() string

type ClientSecretCredential

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

ClientSecretCredential enables authentication to Azure Active Directory using a client secret that was generated for an App Registration. More information on how to configure a client secret can be found here: https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application

func NewClientSecretCredential

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

NewClientSecretCredential constructs a new ClientSecretCredential with the details needed to authenticate against Azure Active Directory with a client secret. tenantID: The Azure Active Directory tenant (directory) ID of the service principal. clientID: The client (application) ID of the service principal. clientSecret: A client secret that was generated for the App Registration used to authenticate the client. options: allow to configure the management of the requests sent to Azure Active Directory.

func (*ClientSecretCredential) GetToken

GetToken obtains a token from Azure Active Directory, using the specified client secret to authenticate. ctx: Context used to control the request lifetime. opts: TokenRequestOptions contains the list of scopes for which the token will have access. Returns an AccessToken which can be used to authenticate service client calls.

type ClientSecretCredentialOptions added in v0.4.0

type ClientSecretCredentialOptions struct {
	azcore.ClientOptions

	// The host of the Azure Active Directory authority. The default is AzurePublicCloud.
	// Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable.
	AuthorityHost AuthorityHost
}

ClientSecretCredentialOptions configures the ClientSecretCredential with optional parameters. All zero-value fields will be initialized with their default values.

type CredentialUnavailableError

type CredentialUnavailableError interface {
	errorinfo.NonRetriable
	CredentialUnavailable()
}

CredentialUnavailableError indicates a credential can't attempt authenticate because it lacks required data or state.

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 be deployed to Azure. It combines credentials suitable for deployed applications with credentials suitable in local development. It attempts to authenticate with each of these credential types, in the following order: - EnvironmentCredential - ManagedIdentityCredential - AzureCLICredential Consult the documentation for these credential types for more information on how they authenticate.

func NewDefaultAzureCredential

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

NewDefaultAzureCredential creates a default credential chain for applications that will be deployed to Azure.

func (*DefaultAzureCredential) GetToken added in v0.12.0

GetToken attempts to acquire a token from each of the default chain's credentials, stopping when one provides a token.

type DefaultAzureCredentialOptions

type DefaultAzureCredentialOptions struct {
	azcore.ClientOptions

	// The host of the Azure Active Directory authority. The default is AzurePublicCloud.
	// Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable.
	AuthorityHost AuthorityHost
	// TenantID identifies the tenant the Azure CLI should authenticate in.
	// Defaults to the CLI's default tenant, which is typically the home tenant of the user logged in to the CLI.
	TenantID string
}

DefaultAzureCredentialOptions contains options for configuring authentication. These options may not apply to all credentials in the default chain.

type DeviceCodeCredential

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

DeviceCodeCredential authenticates a user using the device code flow, and provides access tokens for that user account. For more information on the device code authentication flow see: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code.

func NewDeviceCodeCredential

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

NewDeviceCodeCredential constructs a new DeviceCodeCredential used to authenticate against Azure Active Directory with a device code. options: Options used to configure the management of the requests sent to Azure Active Directory, please see DeviceCodeCredentialOptions for a description of each field.

func (*DeviceCodeCredential) GetToken

GetToken obtains a token from Azure Active Directory, following the device code authentication flow. This function first requests a device code and requests that the user login before continuing to authenticate the device. This function will keep polling the service for a token until the user logs in. scopes: The list of scopes for which the token will have access. The "offline_access" scope is checked for and automatically added in case it isn't present to allow for silent token refresh. ctx: The context for controlling the request lifetime. Returns an AccessToken which can be used to authenticate service client calls.

type DeviceCodeCredentialOptions added in v0.2.2

type DeviceCodeCredentialOptions struct {
	azcore.ClientOptions

	// Gets the Azure Active Directory tenant (directory) ID of the service principal
	// The default value is "organizations". If this value is changed, then also change ClientID to the corresponding value.
	TenantID string
	// Gets the client (application) ID of the service principal
	// The default value is the developer sign on ID for the corresponding "organizations" TenantID.
	ClientID string
	// The callback function used to send the login message back to the user
	// The default will print device code log in information to stdout.
	UserPrompt func(context.Context, DeviceCodeMessage) error
	// The host of the Azure Active Directory authority. The default is AzurePublicCloud.
	// Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable.
	AuthorityHost AuthorityHost
}

DeviceCodeCredentialOptions provide options that can configure DeviceCodeCredential instead of using the default values. All zero-value fields will be initialized with their default values. Please note, that both the TenantID or ClientID fields should changed together if default values are not desired.

type DeviceCodeMessage added in v0.3.0

type DeviceCodeMessage struct {
	// User code returned by the service.
	UserCode string `json:"user_code"`
	// Verification URL where the user must navigate to authenticate using the device code and credentials.
	VerificationURL string `json:"verification_uri"`
	// User friendly text response that can be used for display purposes.
	Message string `json:"message"`
}

DeviceCodeMessage is used to store device code related information to help the user login and allow the device code flow to continue to request a token to authenticate a user.

type EnvironmentCredential added in v0.2.1

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

EnvironmentCredential enables authentication to Azure Active Directory using either ClientSecretCredential, ClientCertificateCredential or UsernamePasswordCredential. This credential type will check for the following environment variables in the same order as listed: - AZURE_TENANT_ID - AZURE_CLIENT_ID - AZURE_CLIENT_SECRET - AZURE_CLIENT_CERTIFICATE_PATH - AZURE_USERNAME - AZURE_PASSWORD NOTE: EnvironmentCredential will stop checking environment variables as soon as it finds enough environment variables to create a credential type.

func NewEnvironmentCredential

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

NewEnvironmentCredential creates an instance that implements the azcore.TokenCredential interface and reads credential details from environment variables. If the expected environment variables are not found at this time, then a CredentialUnavailableError will be returned. options: The options used to configure the management of the requests sent to Azure Active Directory.

func (*EnvironmentCredential) GetToken added in v0.2.1

GetToken obtains a token from Azure Active Directory, using the underlying credential's GetToken method. ctx: Context used to control the request lifetime. opts: TokenRequestOptions contains the list of scopes for which the token will have access. Returns an AccessToken which can be used to authenticate service client calls.

type EnvironmentCredentialOptions added in v0.4.0

type EnvironmentCredentialOptions struct {
	azcore.ClientOptions

	// The host of the Azure Active Directory authority. The default is AzurePublicCloud.
	// Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable.
	AuthorityHost AuthorityHost
}

EnvironmentCredentialOptions configures the EnvironmentCredential with optional parameters. All zero-value fields will be initialized with their default values.

type InteractiveBrowserCredential added in v0.2.1

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

InteractiveBrowserCredential enables authentication to Azure Active Directory using an interactive browser to log in.

func NewInteractiveBrowserCredential added in v0.2.1

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

NewInteractiveBrowserCredential constructs a new InteractiveBrowserCredential with the details needed to authenticate against Azure Active Directory through an interactive browser window. options: configure the management of the requests sent to Azure Active Directory, pass in nil or a zero-value options instance for default behavior.

func (*InteractiveBrowserCredential) GetToken added in v0.2.1

GetToken obtains a token from Azure Active Directory using an interactive browser to authenticate. ctx: Context used to control the request lifetime. opts: TokenRequestOptions contains the list of scopes for which the token will have access. Returns an AccessToken which can be used to authenticate service client calls.

type InteractiveBrowserCredentialOptions added in v0.2.1

type InteractiveBrowserCredentialOptions struct {
	azcore.ClientOptions

	// The Azure Active Directory tenant (directory) ID of the application. Defaults to "organizations".
	TenantID string
	// The ID of the application the user will sign in to. When not set, users will sign in to an Azure development application.
	ClientID string
	// RedirectURL will be supported in a future version but presently doesn't work: https://github.com/Azure/azure-sdk-for-go/issues/15632.
	// Applications which have "http://localhost" registered as a redirect URL need not set this option.
	RedirectURL string
	// The host of the Azure Active Directory authority. The default is AzurePublicCloud.
	// Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable.
	AuthorityHost AuthorityHost
}

InteractiveBrowserCredentialOptions provides optional configuration. Use these options to modify the default pipeline behavior if necessary. All zero-value fields will be initialized with their default values. Please note, that both the TenantID or ClientID fields should changed together if default values are not desired.

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 attempts authentication using a managed identity that has been assigned to the deployment environment. This authentication type works in several managed identity environments such as Azure VMs, App Service, Azure Functions, Azure CloudShell, among others. More information about configuring managed identities can be found here: https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview

func NewManagedIdentityCredential

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

NewManagedIdentityCredential creates a credential instance capable of authenticating an Azure managed identity in any hosting environment supporting managed identities. See https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview for more information about Azure Managed Identity. options: ManagedIdentityCredentialOptions that configure the pipeline for requests sent to Azure Active Directory.

func (*ManagedIdentityCredential) GetToken

GetToken obtains an AccessToken from the Managed Identity service if available. scopes: The list of scopes for which the token will have access. Returns an AccessToken which can be used to authenticate service client calls.

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 parameters that can be used to configure the pipeline used with Managed Identity Credential. All zero-value fields will be initialized with their default values.

type ResourceID added in v0.9.2

type ResourceID string

ResourceID is an identity's resource ID. Use it with ManagedIdentityCredentialOptions, for example: ManagedIdentityCredentialOptions{ID: ResourceID("/subscriptions/...")}

func (ResourceID) String added in v0.12.0

func (r ResourceID) String() string

type UsernamePasswordCredential

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

UsernamePasswordCredential enables authentication to Azure Active Directory using a user's username and password. If the user has MFA enabled this credential will fail to get a token returning an AuthenticationFailureError. Also, this credential requires a high degree of trust and is not recommended outside of prototyping when more secure credentials can be used.

func NewUsernamePasswordCredential

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

NewUsernamePasswordCredential constructs a new UsernamePasswordCredential with the details needed to authenticate against Azure Active Directory with a simple username and password. tenantID: The Azure Active Directory tenant (directory) ID of the service principal. clientID: The client (application) ID of the service principal. username: A user's account username password: A user's account password options: UsernamePasswordCredentialOptions used to configure the pipeline for the requests sent to Azure Active Directory.

func (*UsernamePasswordCredential) GetToken

GetToken obtains a token from Azure Active Directory using the specified username and password. scopes: The list of scopes for which the token will have access. ctx: The context used to control the request lifetime. Returns an AccessToken which can be used to authenticate service client calls.

type UsernamePasswordCredentialOptions added in v0.4.0

type UsernamePasswordCredentialOptions struct {
	azcore.ClientOptions

	// The host of the Azure Active Directory authority. The default is AzurePublicCloud.
	// Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable.
	AuthorityHost AuthorityHost
}

UsernamePasswordCredentialOptions can be used to provide additional information to configure the UsernamePasswordCredential. Use these options to modify the default pipeline behavior through the TokenCredentialcp. All zero-value fields will be initialized with their default values.

Directories

Path Synopsis
cache module

Jump to

Keyboard shortcuts

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