Feature Request: create a New-AzureRmWebAppCertificate
In order to authenticate web apps to other Azure Services using AAD, we often use certificate based authentication. Today, we can add a certificate in /providers/Microsoft.Web/certificates using New-AzureRmWebAppSSLBinding but an AuthN cert is not linked to a valid CNAME/Hostname so although the certificate is uploaded, the cmdlet returns a nasty error. Looking @ https://github.com/Azure/azure-powershell/tree/dev/src/ResourceManager/Websites/Commands.Websites/Cmdlets/Certificates, there is a GetAzureWebAppCertificate, why not have a New and a Remove as well?
@naveedaz can you take a look
@akurmi owns Websites powershell cmdlets Ashish can you take a look?
Thanks for your feedback @mthenot, we already have this item in our backlog. + @ahmedelnably for visibility.
Is there a REST API endpoint we can use to do this in the meantime? I don't see the REST api documentation for web apps online anywhere right now.
Well I have been trying 2 alternative options, only one working.
-
Use New-AzureRmResource.I can create the certificate but I haven’t found a way to link it to the correct web app ☹
-
Use New-AzureRmWebAppSSLBindingIt works but I have to suppress warning & error.
function New-CertificateName { param( <# to be used only with method #> [Parameter(Mandatory = $True)] [string] $HostingEnvironmentProfileName,
[Parameter(Mandatory = $True)]
[string]
$Thumbprint,
[Parameter(Mandatory = $True)]
[string]
$Location,
[Parameter(Mandatory = $True)]
[string]
$ResourceGroupName
)
New-Variable -Name CertNamePostFixSeparator -Option Private -Scope Local -Value "_"
function GenerateCertNamePostFix{
param(
[Parameter(Mandatory = $True)]
[string]
$HostingEnvironmentProfileName,
[Parameter(Mandatory = $True)]
[string]
$CertNamePostFixSeparator,
[Parameter(Mandatory = $True)]
[string]
$Location,
[Parameter(Mandatory = $True)]
[string]
$ResourceGroupName
)
if ($HostingEnvironmentProfileName -eq $null) {$HostingEnvironmentProfileName = ""}
$returnString = '{0}{1}{2}{3}{4}' -f $HostingEnvironmentProfileName, $CertNamePostFixSeparator, $Location, $CertNamePostFixSeparator, $ResourceGroupName
return $returnString
}
$CertNamePostFix = GenerateCertNamePostFix `
-HostingEnvironmentProfileName $HostingEnvironmentProfileName `
-CertNamePostFixSeparator $CertNamePostFixSeparator `
-Location $Location `
-ResourceGroupName $ResourceGroupName
$returnString = '{0}{1}{2}' -f $Thumbprint, $CertNamePostFixSeparator, $CertNamePostFix
return $returnString
} function Add-AzureRMWebAppCertificate { <# .NAME Add-AzureRMWebAppCertificate
.SYNOPSIS Add a certificate to the Web App certificate store.
.SYNTAX
Add-AzureRMWebAppCertificate [-WebApp]
.DESCRIPTION This PS script would add a certificate to the Web App store.
.PREREQUISITES 1. Following Modules must be installed a. AzureRM: https://msdn.microsoft.com/en-us/library/mt125356.aspx
2. User must be logged in using
Login-AzureRmAccount
3. SubscriptionId must be preselected by using the command: Set-AzureRmContext
.PARAMETERS
-WebApp
-Password <string>
Specifies the password of the PFX
Required? True
Position? named
Default value Current DateTime
Accept pipeline input? false
Accept wildcard characters? false
-Thumbprint <string>
Specifies the Thumprint of the certificate to be store in the Web App
Required? True
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? false
-PFXPath <string>
Specifies the path of the PFX file
Required? True
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? false
-DisplayName <string>
Specifies the display name of the Certificate
Required? True
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? false
.INPUTS This script would take the WebApp object, the Thumbprint of the Certificate, the path & the password of the pfx file to be imported and the display name of the certificate. .OUTPUTS This script would add the certificate to the WebApp.
.EXAMPLE
Example 1: Adding Certificate
Add-AzureRMWebAppCertificate [-WebApp] $WebApp [-Password] $Password [-Thumbprint] $Thumbprint [-PFXPath] "path" [-DisplayName] "DisplayName"
.RELATED LINKS Install location for Powershell modules for Azure AD: http://go.microsoft.com/fwlink/p/?linkid=236297 http://www.rahulpnath.com/blog/managing-azure-ad-application-for-key-vault/
#> param( [Parameter(Mandatory = $True)] [array] $WebApp,
[Parameter(Mandatory = $True)]
[string]
$PFXPath,
[Parameter(Mandatory = $True)]
[string]
$Thumbprint,
[Parameter(Mandatory = $True)]
[string]
$Password,
[Parameter(Mandatory = $True)]
[string]
$DisplayName
)
# Script main routine
Set-StrictMode -Version 3
$error.Clear()
#Initialization
$ReturnValue = $false;
try {
<# Option 1: try with New-AzureRmResource.... Does not seem to work :(
$HostingEnvironmentProfileName = $WebApp.hostingEnvironmentProfile.name
$Location = $WebApp.Location
$ResourceGroupName = ($WebApp.ID).split("/")[4]
$CertificateName = New-CertificateName -HostingEnvironmentProfileName $HostingEnvironmentProfileName -Thumbprint $Thumbprint
-Location $Location `
-ResourceGroupName $ResourceGroupName
$pfxBytes = get-content $PFXPath -Encoding Byte -ErrorAction Stop
$props = @{
PfxBlob = [System.Convert]::ToBase64String($pfxBytes)
Password = $Password
HostingEnvironmentProfile = $WebApp.hostingEnvironmentProfile
}
New-AzureRmResource `
-Name $CertificateName `
-Location $Location `
-PropertyObject $props `
-ResourceGroupName $ResourceGroupName `
-ResourceType Microsoft.Web/certificates `
-ApiVersion 2015-08-01 `
-Force `
-ErrorAction Stop
$ReturnValue = $true
#> <# Option 2: try with New-AzureRmWebAppSSLBinding - suppressing CNAME warning & binding error#> $ResourceGroupName = ($WebApp.ID).split("/")[4] $WebAppName = $WebApp.Name
New-AzureRmWebAppSSLBinding `
-CertificateFilePath $PFXPath `
-CertificatePassword $Password `
-Name $DisplayName `
-ResourceGroupName $ResourceGroupName `
-WebAppName $WebAppName `
-ErrorAction Stop `
-WarningAction SilentlyContinue #Suppress the Warning on CNAME record
$ReturnValue = $True
}
catch {
<# need to suppress the error of the SSL Binding - replace the cmdlet when changes#>
$msg = $_
$hostnamemsg = "Hostname '" + $DisplayName + "' does not exist."
if($msg.tostring() -eq $hostnamemsg.tostring()) {
$ReturnValue = $True
}
else {
write-host "Encountered error while uploading the certificate to the WebApp. Error Message is $msg." -ForegroundColor Red
}
}
return $ReturnValue
}
From: Eric Grover [mailto:[email protected]] Sent: Wednesday, April 20, 2016 1:56 AM To: Azure/azure-powershell [email protected] Cc: Marc Thenot [email protected]; Mention [email protected] Subject: Re: [Azure/azure-powershell] Feature Request: create a New-AzureRmWebAppCertificate (#2108)
Is there a REST API endpoint we can use to do this in the meantime? I don't see the REST api documentation for web apps online anywhere right now.
— You are receiving this because you were mentioned. Reply to this email directly or view it on GitHubhttps://github.com/Azure/azure-powershell/issues/2108#issuecomment-212176639
Thanks for the tip @mthenot !
Once you upload a certificate, you can use 'AzureRmWebAppSSLBinding' command to update the SSL bindings (use -Thumbprint option instead -CertificateFilePath and -CertificatePassword)
<# ############################Add pfx certificate#############################> <# .Synopsis Add pfx certificate from KeyVault to WebApp Ssl setting
.Description It will add pfx certificate from KeyVault to WebApp Ssl setting.
.Parameter SubscriptionName Azure Subscription Name where webapp exist
.Parameter $AzureAppSettingColls is AzureAppSetting class type WebApp WebAppResourceGroup Name . AppSetting need to add in webapp AppSettingSecretName is the secret name in Keyvault KeyVault where connection string storage as secret WebAppName is name of web app in connection string need to add WebAppResourceGroup is resource group of Web App
#>
Param(
[Parameter(
Mandatory=$True)]
[String]
$KeyVaultName,
[Parameter(
Mandatory=$True)]
[String]
$WebAppName,
[Parameter(
Mandatory=$True)]
[String]
$WebAppResourceGroup,
[Parameter(
Mandatory=$True)]
[String]
$SubscriptionName,
[Parameter(
Mandatory=$True)]
[String]
$HostName,
[Parameter(
Mandatory=$True)]
[String]
$PfxSecretName,
[Parameter(
Mandatory=$True)]
[String]
$PfxPassword,
[Parameter(
Mandatory=$True)]
[String]
$PfxName
)
function AddPfxToWebAppFromKV
{
[CmdletBinding()]
Param(
[Parameter(
Mandatory=$True)]
[String]
$SubscriptionName,
[Parameter(
Mandatory=$True)]
[String]
$WebAppResourceGroup,
[Parameter(
Mandatory=$True)]
[String]
$WebAppName,
[Parameter(
Mandatory=$True)]
[String]
$HostName,
[Parameter(
Mandatory=$True)]
[String]
$KeyVaultName,
[Parameter(
Mandatory=$True)]
[String]
$PfxSecretName,
[Parameter(
Mandatory=$True)]
[String]
$PfxPassword,
[Parameter(
Mandatory=$True)]
[String]
$PfxName
)
Process
{
#Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionName $SubscriptionName
#Pfx certificate password
$pfxpass = (Get-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $PfxPassword).SecretValueText
#Added certificate as secreat instead of certificate , retriving certificate as byte array.
$secretRetrieved = (Get-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $PfxSecretName).SecretValueText
$currentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
$kvSecretBytes = [System.Convert]::FromBase64String($secretRetrieved )
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certCollection.Import($kvSecretBytes,$null,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$protectedCertificateBytes = $certCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $PfxPassword)
$pfxPath = $currentDirectory + "\" + $PfxName + ".pfx"
[System.IO.File]::WriteAllBytes($pfxPath, $protectedCertificateBytes)
Write-Output "Resource Goroup Name : $WebAppResourceGroup"
Write-Output "WebApp Name : $WebAppName"
Write-Output "Pfx file temp path : $pfxPath"
try
{
New-AzureRmWebAppSSLBinding -ResourceGroupName $WebAppResourceGroup -WebAppName $WebAppName -CertificateFilePath $pfxPath -CertificatePassword $PfxPassword -Name $HostName -SslState SniEnabled -ErrorAction SilentlyContinue
}
catch
{
#Supress error related to host name and Cetificate thumbprint doesnot match
}
#Retrive exsiting App setting from Web App otherwise Set-AzureRmWebApp command delete existing Appsetting and write new . Add new App setting WEBSITE_LOAD_CERTIFICATES
$hash = @{}
$webApp = Get-AzureRMWebApp -ResourceGroupName $WebAppResourceGroup -Name $WebAppName
$appSettingList = $webApp.SiteConfig.AppSettings
#Add to hashtable
ForEach ($kvp in $appSettingList)
{
$hash[$kvp.Name] = $kvp.Value
}
#Add new Appsetting
$hash['WEBSITE_LOAD_CERTIFICATES']= "*"
#Add All Appsetting collection in WebApp blade under Appsetting
Set-AzureRmWebApp -AppSettings $hash -Name $WebAppName -ResourceGroupName $WebAppResourceGroup
}
}
AddPfxToWebAppFromKV -SubscriptionName $SubscriptionName -WebAppName $WebAppName -WebAppResourceGroup $WebAppResourceGroup -KeyVaultName $KeyVaultName -PfxPassword $PfxPassword -PfxSecretName $PfxSecretName -HostName $HostName -PfxName $PfxName
[System.IO.File]::WriteAllBytes($pfxPath, $protectedCertificateBytes)
@atd80 as a minor enhancement, I'd recommend deleting the pfx file after upload for security reasons.
Closing this issue - since work arounds were provided here.