Friday, November 13, 2020

Azure PowerShell to automate security setup for Azure API Management REST API

Looks like I haven't blogged here in quite a while! 

Hello there! 

Now I am back with the new stuff - I have developed an intense interest in Azure. 

So I will be adding a few blog posts related to my happy moments with Azure. 

In this post I am describing how to setup security required for the use of Azure Management REST API. I want to be able to start my Data Factory from my on-premises orchestration tool, and I am using Azure API Management REST APIs to do that. 

First of all, I need to set the security with the Security Principal in Azure to be able to login to Azure REST API with client secret. 

 See below the script that 

  1.  Installs AzureAD module and connects to the tenant 
    
    Install-Module AzureAD
    
    
    Connect-AzureAD -TenantId "00000-0000-0000-000-0000"
    
  2. Registers application in Azure AD 
    
    $subscriptionId = "00000-0000-0000-000-0000"
    $resourceGroup = "RG"
    $factory = "DF"
    $keyVaultName = "KV"
    
    $appName = "appreg"
    
    $appReg = New-AzureADApplication -DisplayName $appName -AvailableToOtherTenants $false
    
    $appReg
    
  3. Creates a Service Principal for this application 
    
    New-AzADServicePrincipal -ApplicationId $appReg.AppId -Scope "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.DataFactory/factories/$factory"
    
  4. Creates a new client secret 
    
    $startDate = Get-Date
    $endDate = $startDate.AddYears(100)
    $aadAppsecret = New-AzureADApplicationPasswordCredential -ObjectId $appReg.ObjectId -CustomKeyIdentifier "SecretFactoryContributor" -StartDate $startDate -EndDate $endDate
    
  5. Saves this new Client Secret and Client Id in the Key Vault for the use in Azure Management REST APIs
    
    $secret_value = $aadAppsecret.Value
    
    $Secret = ConvertTo-SecureString -String $secret_value -AsPlainText -Force
    Set-AzKeyVaultSecret -VaultName $keyVaultName -Name 'FactoryContributorClientSecret' -ContentType "Client Secret used to get token for Application $appName " -SecretValue $Secret
    
    $secret_value = $appReg.AppId
    
    $Secret = ConvertTo-SecureString -String $secret_value -AsPlainText -Force
    Set-AzKeyVaultSecret -VaultName $keyVaultName -Name 'FactoryContributorClientId' -ContentType "Client Id used to get token for Application $appName " -SecretValue $Secret
    
    

Having this script ready will save me some time when setting up new Azure environments and ensure that I have same settings everywhere. I am not a fan of manual setups!