Category Archives: Programming

Safely Storing Azure App Connection Secrets

Microsoft’s Azure AD surfaces a wide variety of capabilities that can be accessed programmatically via RESTful web APIs. The Azure Graph and its successor the Microsoft Graph are two of the more comprehensive APIs that enable the manipulation of most AAD objects. Using these APIs requires obtaining an OAuth access token to send with API requests. AAD uses two object types to provide the mechanism for obtaining OAuth tokens: Applications and Service Principals. An Application object can span multiple AAD tenants whereas the Service Principal is the tenant-specific representation of the application.

To obtain an OAuth access token, one must call the Microsoft authorization server endpoint to request it. This call must be authenticated by providing the Application’s client ID and client secret. These two values are the app’s credentials and must be protected as you would protect any other privileged credentials. This becomes a problem if you have automated tasks that need to connect to Azure. How can these credentials be safely stored?

The naive programmer would just embed these values into the task’s code. This is especially egregious if the code is checked into a source library because then the secrets will be in the change history even if they are later removed from the code. The first refinement is to put the secrets into a task configuration file. That’s fine as long as the configuration file is never checked into the source library or otherwise stored in an insecure fashion.

It turns out there is a much better solution. X509 certificates are designed to store secret keys and can be used for AAD OAuth token requests. The first step, after a suitable certificate is created1, is to add the certificate as an app access key2 using either the Azure Portal GUI4 or PowerShell. Then you need to install the cert, with private key, into the cert store of the server on which the task will run. Make certain to grant private key access to the service account being used to run the task. Refer to the article in the second footnote for an example of using this technique in C# code.

Using Certificate-based Authentication From PowerShell

The AzureAD PowerShell module wraps the functionality of the MS Graph. A connection to Azure must be made before any of the AzureAD commandlets can be called. The Connect-AzureAD3 commandlet is used to do this. In reality, what it is doing is obtaining and storing an OAuth access token in the PS session. I use the following bit of code to do this:

Import-Module AzureAD
# Check if there is a connection to AAD. If this call throws, then make the connection.
try {
    Get-AzureADCurrentSessionInfo | Out-Null
catch {
    # Use cert-based auth via the AAD app. Ensure that the
    # task context account has access to the cert private key.
    Write-Output "Connecting to AAD"
    $tenantId = ''
    $appId = ''
    $certThumbprint = ''
    Connect-AzureAD -TenantId $tenantId -ApplicationId $appId -CertificateThumbprint $certThumbprint

First this code tries to make an AAD call (Get-AzureADCurrentSessionInfo). That call will fail and throw an exception if there is no valid OAuth token. If that is the case, then the code in the catch block will make the connection and obtain the token using the certificate. Note that you will need to fill in the missing tenantId, appId, and certThumbprint values.

The try/catch setup allows you to run this code multiple times in the same PS session such that it will only attempt to make a connection if there isn’t a valid token.

Unfortunately there are still many functions related to Exchange Online and other Office 365 apps that are not currently manageable by the AzureAD module. For these operations one must revert to the older MSOnline PS module. It employs the Connect-MsolService commandlet to make the connection to Azure but it does not support using certificates to store an app secret.

Using a certificate as the Azure app secret store has many advantages. It provides multiple levels of security. The private key is stored only on the server running the tasks. The private key is protected by ACLs that only grant access to the accounts that are configured to have access. I recommend storing the certificate with the private key set as exportable but protected by a password. That way you can move the tasks and the cert to another server if needed. If you are truly paranoid you can skip this step since it is pretty easy to repeat the steps of creating a self-signed cert and adding it as a secret key to the Application object.


  1. A self-signed certificate is fine for this use. Creating a self-signed cert is pretty straightforward. This article explains one way to do this:
  2. This article uses a sample daemon app to describes using a certificate for API access and goes into the details of every step:
  3. The MS docs for the Connect-AzureAD commandlet also show how to do this from PowerShell although I wasn’t able to get every step of the sample to work as expected.
  4. The Azure Portal GUI for setting a certificate as an Application secret Key:

    Note the “Upload Public Key” button that enables selecting a cert file that contains the public key.

Modifying a Collection While Iterating Over It

I was recently bitten by a bug in some code I had modified. The error message was:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Here is the offending code:

PropertyValueCollection existingProxyAddresses = ADEntry.Properties["proxyAddresses"];
foreach (string proxy in existingProxyAddresses) {
    if (proxy.StartsWith("smpt:")) {

A little head scratching preceded the “Ah ha!” moment when I realized that the initial assignment of the proxyAddresses property to existingProxyAddresses was a simple alias, it was not a copy of the collection. The fix of course was to iterate over a copy of the collection.

The fact that this is AD code is not really not relevant except that the ProperyValueCollection type is a subclass of a collection primitive that doesn’t support LINQ. I would have preferred to used a LINQ extension to create the copy of the collection. PropertyValueCollection does have a CopyTo method so I used that instead but that requires pre-creating the target collection thus:

var existingProxyAddresses = new object[ADEntry.Properties[AdAttributes.ProxyAddress].Count];
ADEntry.Properties[AdAttributes.ProxyAddress].CopyTo(existingProxyAddresses, 0);

Note that the CopyTo method expects an array as the target type. Also note that although I show a string for the property name in the first code snippet, I am actually using a string constant in a class I’ve declared for that purpose.

So why can’t you modify a collection while you are iterating over it? I don’t know the formal reason but I suspect it is because a collection has no defined order. Because of this lack of ordering, the IEnumerator.MoveNext() method, which is used by the foreach statement, won’t have a defined meaning if elements are removed from the collection during the enumeration. As an example, suppose the foreach enumeration was coded to internally copy the collection and iterate over that copy. If its internal order was A, B, C, D and you removed C from the underlying collection, what would happen if the enumerator went to C? It would be undefined. Thus you are prevented from doing this.