1# Azure Identity Client Module for Go
2
3[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/azidentity)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity)
4[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/go/go%20-%20azidentity?branchName=main)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=1846&branchName=main)
5[![Code Coverage](https://img.shields.io/azure-devops/coverage/azure-sdk/public/1846/main)](https://img.shields.io/azure-devops/coverage/azure-sdk/public/1846/main)
6
7The `azidentity` module provides a set of credential types for use with
8Azure SDK clients that support Azure Active Directory (AAD) token authentication.
9
10[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/azidentity)
11| [Azure Active Directory documentation](https://docs.microsoft.com/azure/active-directory/)
12
13# Getting started
14
15## Install the package
16
17This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management.
18
19Install the Azure Identity module:
20
21```sh
22go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity
23```
24
25## Prerequisites
26
27- an [Azure subscription](https://azure.microsoft.com/free/)
28- Go 1.13 or above
29
30### Authenticating during local development
31
32When debugging and executing code locally it is typical for developers to use
33their own accounts for authenticating calls to Azure services. The `azidentity`
34module supports authenticating through developer tools to simplify
35local development.
36
37#### Authenticating via the Azure CLI
38
39`DefaultAzureCredential` and `AzureCLICredential` can authenticate as the user
40signed in to the [Azure CLI][azure_cli]. To sign in to the Azure CLI, run
41`az login`. On a system with a default web browser, the Azure CLI will launch
42the browser to authenticate a user.
43
44![Azure CLI Account Sign In](img/AzureCLILogin.png)
45
46When no default browser is available, `az login` will use the device code
47authentication flow. This can also be selected manually by running `az login --use-device-code`.
48
49![Azure CLI Account Device Code Sign In](img/AzureCLILoginDeviceCode.png)
50
51## Key concepts
52
53### Credentials
54
55A credential is a type which contains or can obtain the data needed for a
56service client to authenticate requests. Service clients across the Azure SDK
57accept a credential instance when they are constructed, and use that credential
58to authenticate requests.
59
60The `azidentity` module focuses on OAuth authentication with Azure Active
61Directory (AAD). It offers a variety of credential types capable of acquiring
62an AAD access token. See [Credential Types](#credential-types "Credential Types") below for a list of this module's credential types.
63
64### DefaultAzureCredential
65The `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.
66
67> 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.
68
69 The `DefaultAzureCredential` will attempt to authenticate via the following mechanisms in order.
70
71![DefaultAzureCredential authentication flow](img/DAC_flow.PNG)
72
73 - Environment - The `DefaultAzureCredential` will read account information specified via [environment variables](#environment-variables) and use it to authenticate.
74 - Managed Identity - If the application is deployed to an Azure host with Managed Identity enabled, the `DefaultAzureCredential` will authenticate with that account.
75 - Azure CLI - If the developer has authenticated an account via the Azure CLI `az login` command, the `DefaultAzureCredential` will authenticate with that account.
76
77
78## Examples
79You can find more examples of using various credentials in [Azure Identity Examples Wiki page](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples).
80
81### Authenticating with `DefaultAzureCredential`
82This example demonstrates authenticating the `ResourcesClient` from the [armresources][armresources_library] module using `DefaultAzureCredential`.
83
84```go
85// The default credential checks environment variables for configuration.
86cred, err := azidentity.NewDefaultAzureCredential(nil)
87if err != nil {
88  // handle error
89}
90
91// Azure SDK Azure Resource Management clients accept the credential as a parameter
92client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil), "<subscription ID>")
93```
94
95See more how to configure the `DefaultAzureCredential` on your workstation or Azure in [Configure DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#configure-defaultazurecredential).
96
97### Authenticating a user assigned managed identity with `DefaultAzureCredential`
98This example demonstrates authenticating the `ResourcesClient` from the [armresources][armresources_library] module using the `DefaultAzureCredential`, deployed to an Azure resource with a user assigned managed identity configured.
99
100See more about how to configure a user assigned managed identity for an Azure resource in [Enable managed identity for Azure resources](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#enable-managed-identity-for-azure-resources).
101
102```go
103// The default credential will use the user assigned managed identity with the specified client ID.
104// The client_ID for the user assigned is set through an environment variable.
105cred, err := azidentity.NewDefaultAzureCredential(nil)
106if err != nil {
107  // handle error
108}
109
110// Azure SDK Azure Resource Management clients accept the credential as a parameter
111client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil), "<subscription ID>")
112```
113
114## Managed Identity Support
115The [Managed identity authentication](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview) is supported via either the `DefaultAzureCredential` or the `ManagedIdentityCredential` directly for the following Azure Services:
116* [Azure Virtual Machines](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token)
117* [Azure App Service](https://docs.microsoft.com/azure/app-service/overview-managed-identity?tabs=dotnet)
118* [Azure Kubernetes Service](https://docs.microsoft.com/azure/aks/use-managed-identity)
119* [Azure Cloud Shell](https://docs.microsoft.com/azure/cloud-shell/msi-authorization)
120* [Azure Arc](https://docs.microsoft.com/azure/azure-arc/servers/managed-identity-authentication)
121* [Azure Service Fabric](https://docs.microsoft.com/azure/service-fabric/concepts-managed-identity)
122
123### Examples
124####  Authenticating in Azure with Managed Identity
125This examples demonstrates authenticating the `ResourcesClient` from the [armresources][armresources_library] 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.
126
127See more about how to configure your Azure resource for managed identity in [Enable managed identity for Azure resources](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#enable-managed-identity-for-azure-resources)
128
129```go
130// Authenticate with a User Assigned Managed Identity.
131cred, err := azidentity.NewManagedIdentityCredential("<USER ASSIGNED MANAGED IDENTITY CLIENT ID>", nil) // specify a client_ID for the user assigned identity
132if err != nil {
133  // handle error
134}
135
136// Azure SDK Azure Resource Management clients accept the credential as a parameter
137client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil), "<subscription ID>")
138```
139
140```go
141// Authenticate with a System Assigned Managed Identity.
142cred, err := azidentity.NewManagedIdentityCredential("", nil) // do not specify a client_ID to use the system assigned identity
143if err != nil {
144  // handle error
145}
146
147// Azure SDK Azure Resource Management clients accept the credential as a parameter
148client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil), "<subscription ID>")
149```
150
151## Credential Types
152
153### Authenticating Azure Hosted Applications
154
155|credential|usage|configuration|example
156|-|-|-|-
157|DefaultAzureCredential|simplified authentication experience to get started developing applications for the Azure cloud|[configuration](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#configure--defaultazurecredential)|[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#authenticating-with-defaultazurecredential)
158|ChainedTokenCredential|define custom authentication flows composing multiple credentials||[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#chaining-credentials)
159|EnvironmentCredential|authenticate a service principal or user configured by environment variables||
160|ManagedIdentityCredential|authenticate the managed identity of an Azure resource|[configuration](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#enable-managed-identity-for-azure-resources)|[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#authenticating-in-azure-with-managed-identity)
161
162### Authenticating Service Principals
163
164|credential|usage|configuration|example|reference
165|-|-|-|-|-
166|ClientSecretCredential|authenticate a service principal using a secret|[configuration](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#creating-a-service-principal-with-the-azure-cli)|[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#authenticating-a-service-principal-with-a-client-secret)|[Service principal authentication](https://docs.microsoft.com/azure/active-directory/develop/app-objects-and-service-principals)
167|CertificateCredential|authenticate a service principal using a certificate|[configuration](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#creating-a-service-principal-with-the-azure-cli)|[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#authenticating-a-service-principal-with-a-client-certificate)|[Service principal authentication](https://docs.microsoft.com/azure/active-directory/develop/app-objects-and-service-principals)
168
169### Authenticating Users
170
171|credential|usage|configuration|example|reference
172|-|-|-|-|-
173|InteractiveBrowserCredential|interactively authenticate a user with the default web browser|[configuration](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#enable-applications-for-interactive-browser-oauth-2-flow)|[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#authenticating-a-user-account-interactively-in-the-browser)|[OAuth2 authentication code](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow)
174|DeviceCodeCredential|interactively authenticate a user on a device with limited UI|[configuration](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#enable-applications-for-device-code-flow)|[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#authenticating-a-user-account-with-device-code-flow)|[Device code authentication](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-device-code)
175|UsernamePasswordCredential|authenticate a user with a username and password||[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#authenticating-a-user-account-with-username-and-password)|[Username + password authentication](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth-ropc)
176|AuthorizationCodeCredential|authenticate a user with a previously obtained authorization code as part of an Oauth 2 flow|[configuration](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#enable-applications-for-oauth-2-auth-code-flow)||[OAuth2 authentication code](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow)
177
178### Authenticating via Development Tools
179
180|credential|usage|configuration|example|reference
181|-|-|-|-|-
182|AzureCLICredential|authenticate as the user signed in to the Azure CLI|[configuration](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#sign-in-azure-cli-for-azureclicredential)|[example](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples#authenticating-a-user-account-with-azure-cli)|[Azure CLI authentication](https://docs.microsoft.com/cli/azure/authenticate-azure-cli)
183
184## Environment Variables
185
186DefaultAzureCredential] and
187EnvironmentCredential can be configured with
188environment variables. Each type of authentication requires values for specific
189variables:
190
191#### Service principal with secret
192|variable name|value
193|-|-
194|`AZURE_CLIENT_ID`|id of an Azure Active Directory application
195|`AZURE_TENANT_ID`|id of the application's Azure Active Directory tenant
196|`AZURE_CLIENT_SECRET`|one of the application's client secrets
197
198#### Service principal with certificate
199|variable name|value
200|-|-
201|`AZURE_CLIENT_ID`|id of an Azure Active Directory application
202|`AZURE_TENANT_ID`|id of the application's Azure Active Directory tenant
203|`AZURE_CLIENT_CERTIFICATE_PATH`|path to a PEM-encoded certificate file including private key (without password protection)
204
205#### Username and password
206|variable name|value
207|-|-
208|`AZURE_CLIENT_ID`|id of an Azure Active Directory application
209|`AZURE_USERNAME`|a username (usually an email address)
210|`AZURE_PASSWORD`|that user's password
211
212Configuration is attempted in the above order. For example, if values for a
213client secret and certificate are both present, the client secret will be used.
214
215## Troubleshooting
216
217### Error Handling
218
219Credentials return `CredentialUnavailableError` when they're unable to attempt
220authentication because they lack required data or state. For example,
221`NewEnvironmentCredential` will return an error when
222[its configuration](#environment-variables "its configuration") is incomplete.
223
224Credentials return `AuthenticationFailedError` when they fail
225to authenticate. Call `Error()` on `AuthenticationFailedError` to see why authentication failed. When returned by
226`DefaultAzureCredential` or `ChainedTokenCredential`,
227the message collects error messages from each credential in the chain.
228
229For more details on handling specific Azure Active Directory errors please refer to the
230Azure Active Directory
231[error code documentation](https://docs.microsoft.com/azure/active-directory/develop/reference-aadsts-error-codes).
232
233### Logging
234
235This 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 `LogCredential`.
236Credentials log basic information only, including `GetToken` success or failure and errors. These log entries do not contain authentication secrets but may contain sensitive information.
237
238To 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` classificatons. A logger that only includes credential logs can be like the following:
239
240```go
241import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
242// Set log to output to the console
243azlog.SetListener(func(cls LogClassification, s string) {
244		fmt.Println(s) // printing log out to the console
245  })
246
247// Include only azidentity credential logs
248azlog.SetClassifications(azidentity.LogCredential)
249```
250
251> CAUTION: logs from credentials contain sensitive information.
252> These logs must be protected to avoid compromising account security.
253
254## Next steps
255
256The Go client libraries listed [here](https://azure.github.io/azure-sdk/releases/latest/go.html) 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](https://azure.github.io/azure-sdk/releases/latest/go.html).
257
258## Provide Feedback
259
260If you encounter bugs or have suggestions, please
261[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Azure.Identity` label.
262
263## Contributing
264
265This project welcomes contributions and suggestions. Most contributions require
266you to agree to a Contributor License Agreement (CLA) declaring that you have
267the right to, and actually do, grant us the rights to use your contribution.
268For details, visit [https://cla.microsoft.com](https://cla.microsoft.com).
269
270When you submit a pull request, a CLA-bot will automatically determine whether
271you need to provide a CLA and decorate the PR appropriately (e.g., label,
272comment). Simply follow the instructions provided by the bot. You will only
273need to do this once across all repos using our CLA.
274
275This project has adopted the
276[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
277For more information, see the
278[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
279or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any
280additional questions or comments.
281
282[azure_cli]: https://docs.microsoft.com/cli/azure
283[armresources_library]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resources/armresources
284[azblob]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk
285
286![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fidentity%2Fazure-identity%2FREADME.png)
287