Authenticate with the Azure Libraries for .NET

Connect to services with connection strings

Most Azure service libraries require a connection string or keys for authentication. For example, SQL Database uses a standard SQL connection string:

var builder = new SqlConnectionStringBuilder();
builder.DataSource = "example.database.windows.net";
builder.InitialCatalog = "MyDatabase";
builder.UserID = "sampleuser@example"; // Format user ID as "user@server"
builder.Password = password;
builder.Encrypt = true;
builder.TrustServerCertificate = true;
                
using (var conn = new SqlConnection(builder.ConnectionString))
{
    conn.Open();
    // Do things with the connection...
    // ...
}

Azure Storage uses a storage key:

string storageConnectionString = "DefaultEndpointsProtocol=https;"
        + "AccountName=" + storageName
        + ";AccountKey=" + storageKey
        + ";EndpointSuffix=core.windows.net";

var account = CloudStorageAccount.Parse(storageConnectionString);
// Do things with the account here...

Service connection strings are used in other Azure services like CosmosDB, Redis Cache, and Service Bus and 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.

This snippet uses the management libraries to create a storage account connection string:

// Get a storage account
var storage = azure.StorageAccounts.GetByResourceGroup("myResourceGroup", "myStorageAccount");

// Extract the keys
var storageKeys = storage.GetKeys();

// Build the connection string
string storageConnectionString = "DefaultEndpointsProtocol=https;"
        + "AccountName=" + storage.Name
        + ";AccountKey=" + storageKeys[0].Value
        + ";EndpointSuffix=core.windows.net";

// Connect
var account = CloudStorageAccount.Parse(storageConnectionString);

// Do things with the account here...

Other libraries require your application to run with a service principal authorizing the application to run with granted credentials. This configuration is similar to the object-based authentication steps for the management library listed below.

Azure management libraries for .NET authentication

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();

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();