I have an Azure PowerShell task in my pipeline, in which I need to import a certificate to a key vault. Before doing that, I need to assign Import certificate permission to the current service principal. However, this service principal might already have existing certificate permissions (e.g. Get, List) from other tasks in this or other pipelines. If I use Set-AzKeyVaultAccessPolicy, it will remove these other permissions. Is there a way of preserving these permissions, and just adding some new ones?
$spId = (Get-AzContext).Account.Id;
Set-AzKeyVaultAccessPolicy -VaultName $kv -ServicePrincipalName $spId -PermissionsToCertificates Import
Import-AzKeyVaultCertificate -VaultName $kv …
There is no direct way to add the new permission, your option is to get the old permissions as a list, add the new permission to it, then set all the permissions again.
The sample works for me:
$spId = (Get-AzContext).Account.Id
$objectid = (Get-AzADServicePrincipal -ApplicationId $spId).Id
$kv = Get-AzKeyVault -ResourceGroupName <group-name> -VaultName joykeyvault
$cerpermission = ($kv.AccessPolicies | Where-Object {$_.ObjectId -eq $objectid}).PermissionsToCertificates
$cerpermission += "Import"
Set-AzKeyVaultAccessPolicy -VaultName joykeyvault -ObjectId $objectid -BypassObjectIdValidation -PermissionsToCertificates $cerpermission
Note: The parameters in the last line is important, if your service principal used in the devops service connection does not have the permission to list service principals in your AAD tenant, please use -ObjectId $objectid -BypassObjectIdValidation instead of -ServicePrincipalName $spId, otherwise you will get an error.
Related
when we create an azure ad app registration from the azure portal the service principal is automatically created, and given a contributors role, how do we achieve the same using PowerShell ?
I tried running the following the command the app is created but no service principal is created, and there are no parameters for configuring a service principle
New-AzADApplication -DisplayName "NewApplication" -HomePage "http://www.microsoft.com" -IdentifierUris "http://NewApplication"
what i am looking for is to create the following using powershell, is this possible ?
AzureADAppregistration + ServicePrincipal
Create and get the client secret
Thanks
Try this:
#set your secret here.
$secretTextValue = "abcdefg1234567890"
$secret = ConvertTo-SecureString -String $secretTextValue -AsPlainText
$app = New-AzADApplication -DisplayName "NewApplication" -HomePage "http://www.microsoft.com" -IdentifierUris "http://NewApplication"
New-AzADAppCredential -ObjectId $app.ObjectId -Password $secret -EndDate (Get-Date).AddMonths(6)
#azure will assign contributor role of current subscription to this SP
New-AzADServicePrincipal -ApplicationId $app.ApplicationId
Result:
I added two accounts through powershell from devops yaml pipeline:
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ObjectId $obj1 -PermissionsToSecrets Set,Get -BypassObjectIdValidation
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ObjectId $obj2 -PermissionsToSecrets Set,Get -BypassObjectIdValidation
$obj1 = ADF
$obj2 = Pipeline Application identity
Obj1(ADF) came in 'Application' section of the access policy of Key Vault
But Obj2 came in 'Unknown'section why?
Once Obj2 also came in 'Compound Identity' section .. not sure why
If you are adding an Access Policy to Key Vault for an AAD application/service principal, make sure to use the ObjectId of the service principal, which is a different ObjectId than that of the application. You can use Get-AzADServicePrincipal to retrieve the service principal and find its ObjectId.
I have a service principal that I've creating using below powershell.
$sp3 = New-AzureRmADServicePrincipal `
-DisplayName "<service-principal-name>" `
-CertValue $certValue3 `
-EndDate ([System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($cert3.Certificate.GetExpirationDateString(), [System.TimeZoneInfo]::Local.Id, 'GMT Standard Time'))
where certValue3 is Base64String RawCertData. This service principal works fine and I am able to get a token when using the cert.
Once service principal is created in Azure AD, how do I see thumbprint of the certificate associated with the service principal using Powershell?
I've tried this, but I get Forbidden when I try to execute Get-AzureADApplicationKeyCredential
I also checked the manifest in Azure Portal under the service principal that gets created under Azure Active Directory → App Registrations → <service-principal-name> → Manifest, but the keyCredentials node is empty
"keyCredentials": [],
Please note that when I create an application using New-AzureRmADApplication followed by credential New-AzureRmADAppCredential and then New-AzureRmADServicePrincipal, then I see the keyCredentials with customKeyIdentifier set to the certificate thumbprint. Sample script below -
$adapp = New-AzureRmADApplication -DisplayName "<application-name>" `
-HomePage "<home-page-url>" `
-IdentifierUris "<identifier-url>" `
-CertValue $certValue `
-StartDate ([System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($cert.Certificate.GetEffectiveDateString(), [System.TimeZoneInfo]::Local.Id, 'GMT Standard Time')) `
-EndDate ([System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($cert.Certificate.GetExpirationDateString(), [System.TimeZoneInfo]::Local.Id, 'GMT Standard Time'))
New-AzureRmADAppCredential -ApplicationId $adapp.ApplicationId -CertValue $certValue2
$sp2 = New-AzureRmADServicePrincipal -ApplicationId $adapp.ApplicationId -DisplayName "<application-name>"
How to get thumbprint of the certificate associated with a service principal in Azure AD using powershell when the service principal is created independently without AzureRmADApplication and AzureRmADAppCredential?
According to my test, we can use the following Azure AD Graph API to get the key credentials of the sp. The customKeyIdentifier in KeyCredential is the thumbprint of the certificate
GET https://graph.windows.net/<your teanant id>/servicePrincipals/<your sp object id>/keyCredentials?api-version=1.6
For example
Create sp and get thumbprint
$tenantId ="<tenant id>"
#use the goabl admin account to login
Connect-AzureRmAccount -Tenant $tenantId
$certificateObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certificateObject.Import("E:\Cert\examplecert.pfx","Password0123!", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
Write-Host "the thumbrint of cert"
$certificateObject.Thumbprint
$keyValue = [System.Convert]::ToBase64String($certificateObject.GetRawCertData())
$sp =New-AzureRmADServicePrincipal -DisplayName "jimtestsample" -CertValue $keyValue -EndDate $endDate
$context=Get-AzureRmContext
$token=$context.TokenCache.ReadItems() |Where-Object { ($_.TenantId -eq $tenantId) -and ($_.Resource -eq "https://graph.windows.net/") }
$accesstoken=$token.AccessToken
$url = "https://graph.windows.net/$tenantId/servicePrincipals/"+$sp.Id+"/keyCredentials?api-version=1.6"
$keyCreds = Invoke-RestMethod -Uri $url -Method Get -Headers #{"Authorization" = "Bearer $accesstoken"}
Write-Host "--------------------------------------------"
$keyCreds.value | Select-Object customKeyIdentifier
I test your command, it should work. When using New-AzADServicePrincipal to create the service principal, it will create an AD App(i.e. App Registration) for you automatically, and the certificate will also appear in the Certificates & secrets of your AD App.
In my sample, I use the new Az module, for the old AzureRm module which you used, it should also work(Not completely sure, I recommend you to use the new Az module, because the AzureRm module has been deprecated and will not be updated). And make sure you are looking into the correct AD App in the portal, because the DisplayName of the AD App could be repeated.
$cert=New-SelfSignedCertificate -Subject "CN=TodoListDaemonWithCert" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature
$bin = $cert.RawData
$base64Value = [System.Convert]::ToBase64String($bin)
New-AzADServicePrincipal -DisplayName joy134 -CertValue $base64Value
Check in the portal:
Then you can use this way you have tried, to fix the Forbidden error, your account should at least be the Owner of the AD App, or if your account has an admin role in the tenant e.g. Application administrator, Groups administrator, it will also work.
$CustomKeyIdentifier = (Get-AzureADApplicationKeyCredential -ObjectId "<object-id>").CustomKeyIdentifier
$Thumbprint = [System.Convert]::ToBase64String($CustomKeyIdentifier)
Besides, you should note the different command combinations will lead to different results, see this link. So when you test it, I recommend you to use different values of the parameters.
I am looking for an example of using a certificate to authenticate to the keyvault, and then get a secret -- all in PowerShell (already have operational C#).
Have an app in AD for accessing Keyvault.
First, make sure your AD App(service principal) has the correct permission in your keyvault -> Access policies, in your case, it should be Get and List secret permissions.
Then get values for signing in and try the command as below.
Connect-AzAccount -CertificateThumbprint "<certificate Thumbprint>" -ApplicationId "<AD App applicationid(clientid)>" -Tenant "<tenant id>" -ServicePrincipal
Get-AzKeyVaultSecret -VaultName "<keyvault name>" -Name "<secret name>" -Version "<secret version>" | ConvertTo-Json
We bought a certificate via Azure and would like to use it on same VM.
We just need .pfx file.
We tried almost everything and we are getting next error:
"You do not have permission to get the service prinicipal information
needed to assign a Key Vault to your certificate. Please login with an
account which is either the owner of the subscription or an admin of
the Active Directory to configure Key Vault settings."
But we have permissions...
#Sasha, there are not a lot of details to go on here and I hate to state the obvious given you've tried everything, but the error message is pretty clear - "You do not have permission to get the service principal information needed".
Some things to clarify and check:
Did you buy an Azure "App Service Certificate"?
Is the certificate in 'issued' status?
Are you logged in as the subscription owner or did the owner give you admin access to their subscription? The latter is not good enough, I believe.
Did you complete the three-step validation process?
If you did all of that, your certificate is now stored in an Azure Key Vault. When you create an Azure Key Vault, there is an advanced access policy option to "Enable Access to Azure Virtual Machines for deployment" (see image). Its help info reads, "Specifies whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault."
That said, since you want a .pfx file, below is a sample PowerShell script extracted from MSDN blogs to do just that. Provide appropriate values for the four "$" parameters below and save the script as copyasc.ps1.
$appServiceCertificateName = ""
$resourceGroupName = ""
$azureLoginEmailId = ""
$subscriptionId = ""
Login-AzureRmAccount
Set-AzureRmContext -SubscriptionId $subscriptionId
$ascResource = Get-AzureRmResource -ResourceName $appServiceCertificateName -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.CertificateRegistration/certificateOrders" -ApiVersion "2015-08-01"
$keyVaultId = ""
$keyVaultSecretName = ""
$certificateProperties=Get-Member -InputObject $ascResource.Properties.certificates[0] -MemberType NoteProperty
$certificateName = $certificateProperties[0].Name
$keyVaultId = $ascResource.Properties.certificates[0].$certificateName.KeyVaultId
$keyVaultSecretName = $ascResource.Properties.certificates[0].$certificateName.KeyVaultSecretName
$keyVaultIdParts = $keyVaultId.Split("/")
$keyVaultName = $keyVaultIdParts[$keyVaultIdParts.Length - 1]
$keyVaultResourceGroupName = $keyVaultIdParts[$keyVaultIdParts.Length - 5]
Set-AzureRmKeyVaultAccessPolicy -ResourceGroupName $keyVaultResourceGroupName -VaultName $keyVaultName -UserPrincipalName $azureLoginEmailId -PermissionsToSecrets get
$secret = Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $keyVaultSecretName
$pfxCertObject=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList #([Convert]::FromBase64String($secret.SecretValueText),"", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfxPassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 50 | % {[char]$_})
$currentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[io.file]::WriteAllBytes(".\appservicecertificate.pfx", $pfxCertObject.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $pfxPassword))
Write-Host "Created an App Service Certificate copy at: $currentDirectory\appservicecertificate.pfx"
Write-Warning "For security reasons, do not store the PFX password. Use it directly from the console as required."
Write-Host "PFX password: $pfxPassword"
Type the following commands in PowerShell console to execute the script:
Powershell –ExecutionPolicy Bypass
.\copyasc.ps1
Once the script is executed, you would see a new file in the current directory called ‘appservicecertificate.pfx’. This is a password protected PFX, the PowerShell console would display the corresponding password.