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 PowerShell:

Login-AzureRmAccount

Note the information displayed about your tenant and subscription:

Environment           : AzureCloud
Account               : jane@contoso.com
TenantId              : 43413cc1-5886-4711-9804-8cfea3d1c3ee
SubscriptionId        : 15dbcfa8-4b93-4c9a-881c-6189d39f04d4
SubscriptionName      : my-subscription
CurrentStorageAccount : 

Create a service principal using PowerShell, like this:

# Create the service principal (use a strong password)
$sp = New-AzureRmADServicePrincipal -DisplayName "AzureDotNetTest" -Password "password"

# Give it the permissions it needs...
New-AzureRmRoleAssignment -ServicePrincipalName $sp.ApplicationId -RoleDefinitionName Contributor

# Display the Application ID, because we'll need it later.
$sp | Select DisplayName, ApplicationId

Make sure to note the ApplicationId:

DisplayName     ApplicationId
-----------     -------------
AzureDotNetTest a2ab11af-01aa-4759-8345-7803287dbd39

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

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);
  • clientId: use the ApplicationId value from the service principal output.
  • clientSecret: use the -Password parameter you assigned when you ran New-AzureRmADServicePrincipal (without quotes).
  • tenantId: use the TenantId value from when you ran Login-AzureRmAccount.

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

var azure = 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.properties using the service principal credentials:

# sample management library properties file
subscription=15dbcfa8-4b93-4c9a-881c-6189d39f04d4
client=a2ab11af-01aa-4759-8345-7803287dbd39
key=password
tenant=43413cc1-5886-4711-9804-8cfea3d1c3ee
managementURI=https://management.core.windows.net/
baseURL=https://management.azure.com/
authURL=https://login.windows.net/
graphURL=https://graph.windows.net/
  • subscription: use the SubscriptionId value from when you ran Login-AzureRmAccount.
  • client: use the ApplicationId value from the service principal output.
  • key: use the -Password parameter you assigned when you ran New-AzureRmADServicePrincipal (without quotes).
  • tenant: use the TenantId value from when you ran Login-AzureRmAccount.

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.properties", "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 = Azure
    .Configure()
    .Authenticate(credentials)
    .WithDefaultSubscription();