30

I want to automate the creation of my application in Azure AD and get back the client id generated by Azure AD.

Are there PowerShell commandlets to do this? Is there some other means, like an API of doing this besides the management console?

Can you point me to an example?

Thanks!

2

4 Answers 4

45

There are a number of ways you can create an application in AAD Programatically. I will briefly cover two different ways you can go about doing this: PowerShell CMDLETs and the Graph API. In general, I would strongly reccommend using the Graph API for this.

PowerShell:

There are a few different modules running around that have the ability to create AAD Applications/Service Principals. If you need to create a new application object in your tenant, you can use Azure PowerShell to make the following call:

https://msdn.microsoft.com/en-us/library/mt603747.aspx

PS C:\> New-AzureRmADApplication -DisplayName "NewApplication" -HomePage "http://www.Contoso.com" -IdentifierUris "http://NewApplication"

If you need to create a service principal for your application in your tenant you can use Azure AD PowerShell:

https://msdn.microsoft.com/en-us/library/azure/jj151815.aspx

https://msdn.microsoft.com/en-us/library/azure/dn194119.aspx

New-MsolServicePrincipal -ServicePrincipalNames @("MyApp/Contoso.com") -DisplayName "My Application"

Graph API: (recommended)

You can also create applications by making a POST to our Graph API: https://msdn.microsoft.com/Library/Azure/Ad/Graph/api/entity-and-complex-type-reference#ApplicationEntity

We have samples that show how you can register and create an applicatoin to target the Graph API, and use the Graph Client Library to assist you in making the correct calls to the API:

https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet

I hope this helps!

8
  • 2
    Thanks for the answer. I would upvote if I had the reputation.
    – Eric
    Jul 29, 2015 at 0:39
  • if this is the right answer, then as the person who asked the question, you can mark it as the answer. This helps others coming along later and looking at this question.
    – Rich Ross
    Jul 29, 2015 at 11:56
  • To call the GraphAPI to create a new application, do I need a client application registered in Azure AD? Do I need to create that client application in Azure AD via the management portal? Or is there another way to solve this 'bootstrap' problem?
    – Eric
    Jul 29, 2015 at 20:12
  • 2
    Hi Eric, You do need to register a Client ID in order to talk to the Graph API. The normal method to do this is via the Azure Management Portal. If you think you are caught in a "chicken vs egg" scenario, I believe you should be able to create a service princpial using PowerShell, and then give that service principal the permissions to create applications, however I think using the Management portal is a cleaner solution if that fits. Jul 30, 2015 at 1:24
  • 5
    Hi Shawn, The "chicken vs egg" scenario is a problem for an ISV who wants to make it easy for customers to create an application descriptor in their AAD. It's currently not possible to use PowerShell's New-AzureRmAdApplication to define which other APIs the application should have access to. (The "permissions to other applications" section in the Management Portal). It would be great if the Powershell cmdlets could download and upload the application's manifest, to modify all settings of the application.
    – RasmusW
    Jan 8, 2016 at 10:52
5

I'm a little late to the party - but I recently encountered this challenge too. Here are the relevant excerpts from my solution...

First you need to get the authentication token. For this you can use this handy function.

function GetAuthToken
{
       param
       (
              [Parameter(Mandatory=$true)]
              $TenantName
       )

       $adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"

       $adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"

       [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null

       [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

       $clientId = "1950a258-227b-4e31-a9cf-717495945fc2" 

       $redirectUri = "urn:ietf:wg:oauth:2.0:oob"

       $resourceAppIdURI = "https://graph.windows.net"

       $authority = "https://login.windows.net/$TenantName"

       $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority

       $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$redirectUri, "Auto")

       return $authResult
}

(borrowed from Paulo Marques https://blogs.technet.microsoft.com/paulomarques/2016/03/21/working-with-azure-active-directory-graph-api-from-powershell/)

You can then submit a POST request to the Azure Active Directory Graph API in order to create your application. However there is a little setup required.

# The name of this AAD instance
$global:tenant = "mycompany.onmicorosft.com"
$global:aadSecretGuid = New-Guid
$global:aadDisplayName = "azure-ad-displayname"
$global:aadIdentifierUris = @("https://contoso.com")
$guidBytes = [System.Text.Encoding]::UTF8.GetBytes($global:aadSecretGuid)

$global:aadSecret = @{
    'type'='Symmetric';
    'usage'='Verify';
    'endDate'=[DateTime]::UtcNow.AddDays(365).ToString('u').Replace(' ', 'T');
    'keyId'=$global:aadSecretGuid;
    'startDate'=[DateTime]::UtcNow.AddDays(-1).ToString('u').Replace(' ', 'T');  
    'value'=[System.Convert]::ToBase64String($guidBytes);
}

# ADAL JSON token - necessary for making requests to Graph API
$global:token = GetAuthToken -TenantName $global:tenant
# REST API header with auth token
$global:authHeader = @{
    'Content-Type'='application/json';
    'Authorization'=$global:token.CreateAuthorizationHeader()
}

Now you can hit the Graph API.

$resource = "applications"
$payload = @{
    'displayName'=$global:aadDisplayName;
    'homepage'='https://www.contoso.com';
    'identifierUris'= $global:aadIdentifierUris;
    'keyCredentials'=@($global:aadSecret)
}
$payload = ConvertTo-Json -InputObject $payload
$uri = "https://graph.windows.net/$($global:tenant)/$($resource)?api-version=1.6"
$result = (Invoke-RestMethod -Uri $uri -Headers $global:authHeader -Body $payload -Method POST -Verbose).value

Once the response comes back, you can extract the configuration values you need.

# Extract configuration values
$keyObject = foreach($i in $result.keyCredentials) { $i }

# Tenant ID
$global:aadTenantId = Get-AzureRmSubscription | Select-Object -ExpandProperty TenantId
# Application object ID
$global:aadApplicationObjectId = $result | Select-Object -ExpandProperty objectId
# App ID / Client ID
$global:aadClientId = $result | Select-Object -ExpandProperty appId
# Application Secret/Key
$global:aadAppSecret = $keyObject | Select-Object -ExpandProperty keyId

I hope this helps somebody!

1
  • Brilliant answer matt ;-)
    – Thomas
    Aug 25, 2016 at 3:57
2

Microsoft has released a couple of additional PowerShell cmdlets to register an app and set credentials:

New-AzureRmADApplication
New-AzureRmADServicePrincipal
New-AzureRmRoleAssignment 
Add-AzureADApplicationCredential 

Please review their documentation: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal

0

I've written some powershell scripts which will

  • Create AAD applications (thanks mainly to Matt's answer)
  • Create a Key Vault in Azure
  • Create a key in the Key Vault
  • Assign permissions to the key vault for the AAD applications

I know this is more than what you're asking for, but if, like me, you're interested in getting back the secret (aka key) from the application (the same one you add in the portal which you have to copy before never seeing it again), then the second script will allow you to explicitly send that in as part of the payload in a call to the Graph API. The script will save that to a file for you to refer to later.

The other scripts are not really what you're asking about, but you may still find them useful if you ever need to set up SQL Server to work with Azure Key Vault for TDE or column-level encryption.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.