Authenticate with the Azure SDK for .NET

The latest packages in the Azure SDK for .NET use a common authentication package to authenticate, Azure.Identity. Using Azure.Identity is recommended over other authentication mechanisms described later in this document. Packages supporting the credentials provided by Azure.Identity are built on top of Azure.Core and have package identifiers starting with Azure. See the package list for an inventory of packages that use Azure.Core.

For complete instructions on using Azure.Identity in your project, see the documentation for Azure Identity client for .NET.

Tip

See the Azure Identity, Resource Management, and Storage sample for examples of using Azure Identity to manage and access Azure resources.

To authenticate with libraries that don't support Azure.Identity, see the rest of this topic.

Access Azure resources

To interact with Azure resources, such as retrieving a secret from Key Vault or storing a blob in Storage, many Azure service libraries require a connection string or keys for authentication. For example, SQL Database uses a standard SQL connection string. Service connection strings are used in other Azure services like CosmosDB, Azure Cache for Redis, and Service Bus. You can get those strings using the Azure portal, CLI, or PowerShell. You can also use the Azure management libraries for .NET to query resources to build connection strings in your code.

The methods for using a connection string vary by product. Refer to the documentation for your Azure product.

Manage Azure resources

Your .NET application needs permissions to read and create resources in your Azure subscription in order to use the Azure Management Libraries for .NET. Create a service principal and configure your app to run with its credentials to grant this access. Service principals provide a way to create a non-interactive account associated with your identity to which you grant only the privileges your app needs to run.

First, login to Azure Cloud Shell. Verify you are currently using the subscription in which you want the service principal created.

az account show

Your subscription information is displayed.

{
  "environmentName": "AzureCloud",
  "id": "15dbcfa8-4b93-4c9a-881c-6189d39f04d4",
  "isDefault": true,
  "name": "my-subscription",
  "state": "Enabled",
  "tenantId": "43413cc1-5886-4711-9804-8cfea3d1c3ee",
  "user": {
    "cloudShellID": true,
    "name": "jane@contoso.com",
    "type": "user"
  }
}

If you're not logged into the correct subscription, select the correct one by typing az account set -s <name or ID of subscription>.

Create the service principal with the following command:

az ad sp create-for-rbac --sdk-auth

The service principal information is displayed as JSON.

{
  "clientId": "b52dd125-9272-4b21-9862-0be667bdf6dc",
  "clientSecret": "ebc6e170-72b2-4b6f-9de2-99410964d2d0",
  "subscriptionId": "ffa52f27-be12-4cad-b1ea-c2c241b6cceb",
  "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47",
  "activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
  "resourceManagerEndpointUrl": "https://management.azure.com/",
  "activeDirectoryGraphResourceId": "https://graph.windows.net/",
  "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
  "galleryEndpointUrl": "https://gallery.azure.com/",
  "managementEndpointUrl": "https://management.core.windows.net/"
}

Copy and paste the JSON output to a text editor for use later.

Now that the service principal is created, two options are available to authenticate to the service principal to create and manage resources.

For both options you will need to add the following NuGet packages to your project.

Install-Package Microsoft.Azure.Management.Fluent
Install-Package Microsoft.Azure.Management.ResourceManager.Fluent

Authenticate with token credentials

The first method is to build the token credential object in code. You should store the credentials securely in a configuration file, the registry, or Azure KeyVault.

var credentials = SdkContext.AzureCredentialsFactory
    .FromServicePrincipal(clientId,
        clientSecret,
        tenantId,
        AzureEnvironment.AzureGlobalCloud);

Use the clientId, clientSecret, and tenantId values from the JSON output when you created the service principal.

Then create the entry point Azure object to start working with the API:

var azure = Microsoft.Azure.Management.Fluent.Azure
    .Configure()
    .Authenticate(credentials)
    .WithDefaultSubscription();

It is recommended that you explicitly provide the subscriptionId from the JSON output to the Azure object:

var azure = Microsoft.Azure.Management.Fluent.Azure
    .Configure()
    .Authenticate(credentials)
    .WithSubscription(subscriptionId);

File-based authentication

File-based authentication allows you to put the service principal credentials in a plain text file and secure it within the file system.

Create a text file named azureauth.json. Paste the JSON output from when you created the service principal.

Save this file in a secure location on your system where your code can read it. Use PowerShell to set an environment variable named AZURE_AUTH_LOCATION with the full path to the file, for example:

[Environment]::SetEnvironmentVariable("AZURE_AUTH_LOCATION", "C:\src\azureauth.json", "User")

Read the contents of the file and create the entry point Azure object to start working with the API:

// pull in the location of the authentication properties file from the environment
var credentials = SdkContext.AzureCredentialsFactory
    .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

var azure = Microsoft.Azure.Management.Fluent.Azure
    .Configure()
    .Authenticate(credentials)
    .WithDefaultSubscription();