Image
{{'2016-10-31T15:45:43.4214618Z' | utcToLocalDate }}
Ben Howard

Create an Azure Active Directory Application and Key using PowerShell

I’ve been a SQL developer for a good few years now, and have also developed numerous web applications, web services and various console apps. However, lately I find myself getting into the world of DevOps, Azure, and necessarily, PowerShell. Whilst familiar with PowerShell to a degree, I’ve learnt a lot over the past few weeks about the Azure PowerShell module, and how we can use it to script tasks that you might not want to do manually in the Azure portal if you’re thinking about automation.

This post should help if you want to create an Azure Active Directory application using PowerShell and get the application key back for use with authentication later.

In the Portal

Creating an Active Directory application in Azure is a simple affair; once you’ve logged into the portal, you can just go to the Azure Active Directory blade, click on App Registrations, fill in the boxes and hit Create:

image

The created app:

image

You will most likely also want to add a “key” (aka “secret”), which, along with the Application ID can be used to authenticate with. You do this by clicking on All settings and then Keys:

clip_image006

Once you’ve added a description and selected the duration, click Save. The Value column will then be populated with a 44-character key value which, after leaving the blade, you will never see again:

image

After creating a service principal, you can use the Application ID and Key to represent your client application in AAD. In my case, I was using it with SQL Server to play with Extensible Key Management Using Azure Key Vault, so the Key Vault was configured to allow access to the application in order to use the Key Vault Key (not to be confused with the application key!).

 

So, how can this be done with PowerShell?

By this point you may be thinking that this should also be a simple process if, like me, you want to do all the configuration in PowerShell instead of the portal. Well, it turns out that it is, although it might have been nice if the documentation were a little clearer. The 44-character key value which we can easily copy and save elsewhere from the page in the portal is not very easy to come by if you’re trying to find it in PowerShell.

I hoped to find the key using the Get-AzureRmADApplication cmdlet, but it’s not there: 

clip_image010

Was there another way?  When you execute Get-AzureRmADApplication cmdlets, a call is made to the Azure Graph API behind the scenes. You can see this in PowerShell by setting variable $DebugPreference = 'continue' (You can set this back again by running $DebugPreference = 'silentlycontinue'). Here is the same command again with (truncated) output:

clip_image012

This time, you can see a lot more detail about the application. The area in the red box above represents the key I added. The value is returned as ‘null’. It is also possible to see the JSON output using the Graph Explorer, or you can also call it directly using a tool such as Postman (this requires the creation of an access token).

When you hit the following URL:

https://graph.windows.net/[mydomain].onmicrosoft.com/applications?api-version=1.6&$filter=displayname eq 'mynewapp'

..you can see the same output:

image

So it appears that once the application is created, the key value is not displayed in the response from the Graph API call at all. It is not simply the Azure GUI front-end hiding it.  Now that I had a good idea of where it appeared in the JSON for the application entity, I looked at the PasswordCredential parameter in more detail.  The documentation for the New-AzureRmADApplication cmdlet shows that the PasswordCredential parameter takes an array of objects of type PSADPasswordCredential.  I created an object of this type in PowerShell to see its properties:

 

image

From this it isn’t obvious which property I might use to supply the key, especially since there does not appear to be a property called “value” like we see in the JSON output.  The only candidate appeared to be “Password”, so I decided to create the 44-character key myself and pass it in explicitly using the “Password” to see what happened.  To create the key in the correct format, I used  a function I found on github:

function Create-AesManagedObject($key, $IV) {

    $aesManaged = New-Object "System.Security.Cryptography.AesManaged"
    $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
    $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
    $aesManaged.BlockSize = 128
    $aesManaged.KeySize = 256

    if ($IV) {
        if ($IV.getType().Name -eq "String") {
            $aesManaged.IV = [System.Convert]::FromBase64String($IV)
        }
        else {
            $aesManaged.IV = $IV
        }
    }

    if ($key) {
        if ($key.getType().Name -eq "String") {
            $aesManaged.Key = [System.Convert]::FromBase64String($key)
        }
        else {
            $aesManaged.Key = $key
        }
    }

    $aesManaged
}


function Create-AesKey() {
    $aesManaged = Create-AesManagedObject
    $aesManaged.GenerateKey()
    [System.Convert]::ToBase64String($aesManaged.Key)
}

#Create the 44-character key value

$keyValue = Create-AesKey

 

I created the PSADPasswordCredential and populated it with start and end dates, a generated GUID, and my key value:

$psadCredential = New-Object Microsoft.Azure.Commands.Resources.Models.ActiveDirectory.PSADPasswordCredential

$startDate = Get-Date

$psadCredential.StartDate = $startDate

$psadCredential.EndDate = $startDate.AddYears(1)

$psadCredential.KeyId = [guid]::NewGuid()

$psadCredential.Password = $KeyValue

 

I created the application, including the PSADPasswordCredential object as the PasswordCredential parameter:

New-AzureRmADApplication –DisplayName “MyNewApp2”`

                         -HomePage $ApplicationURI `

                         -IdentifierUris $ApplicationURI `

                         -PasswordCredentials $psadCredential

I saved the key value to a file to refer to later:

$keyValue | out-file “c:\someplace\keyvalue.txt”

 

Checking back in the portal, I confirmed that a key had been created for the application:

image

Finally, I tried to authenticate using the application Client Id and Key value and bingo! It worked!

By this point I was able to carry on creating the other Azure resources my PowerShell script so I could set up SQL Server with Extensible Key Management Using Azure Key Vault.

So although it is not explicit in the documentation, and there are currently no examples to be found online, it is certainly possible to create an Azure Active Directory Application and Key using PowerShell.

 

comments powered by Disqus