How to add application to Azure AD programmatically? How to add application to Azure AD programmatically? powershell powershell

How to add application to Azure AD programmatically?


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!


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!


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

New-AzureRmADApplicationNew-AzureRmADServicePrincipalNew-AzureRmRoleAssignment Add-AzureADApplicationCredential 

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