Warning about Breaking changes in the cmdlet 'Get-AzKeyVaultSecret' SecretValueText deprecated Az4.6.1 - azure

I upgraded Az Powershell to 4.6.1 today and started seeing the below warning. The question I have is what I am supposed to do about this warning? I could mute the warning but that wouldn't help me prepare for this breaking change at all. I checked the Az 4.6.1 Microsoft docs and they tell me I should still be using SecretValueText and provide no similar warning about deprecation or any alternative ways to get the secret value. So what is my update path for powershell that reads KeyVault secrets using SecretValueText?
WARNING: Breaking changes in the cmdlet 'Get-AzKeyVaultSecret' :
WARNING: - "The output type 'Microsoft.Azure.Commands.KeyVault.Models.PSKeyVaultSecret' is changing"
- The following properties in the output type are being deprecated :
'SecretValueText'
WARNING: Note :The change is expected to take effect from the version : '3.0.0'
WARNING: - "The output type 'Microsoft.Azure.Commands.KeyVault.Models.PSDeletedKeyVaultSecret' is changing"
- The following properties in the output type are being deprecated :
'SecretValueText'
WARNING: Note :The change is expected to take effect from the version : '3.0.0'
WARNING: NOTE : Go to https://aka.ms/azps-changewarnings for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell.
Here is the current example in the Microsoft docs:
$secret = Get-AzKeyVaultSecret -VaultName 'Contoso' -Name 'ITSecret'
Write-Host "Secret Value is:" $secret.SecretValueText
Secret Value is: P#ssw0rd

This can be done with:
Get the secret with:
$secret = Get-AzKeyVaultSecret -VaultName {YourVaultName} -Name {YourSecret}
$pass = $secret.SecretValue | ConvertFrom-SecureString -AsPlainText
This is the same as
$secret.SecretValueText

Microsoft documentation has now been updated
This example is taken from the latest docs
$secret = Get-AzKeyVaultSecret -VaultName 'Contoso' -Name 'ITSecret'
$secretValueText = '';
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue)
try {
$secretValueText = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
} finally {
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
}
Write-Host "Secret Value is:" $secretValueText
Secret Value is: P#ssw0rd

Well, even if the SecretValueText will be deprecated, there is a way that will always work.
Just use $secret.SecretValue, it is a System.Security.SecureString, we just need to convert it to String, the $Password below is what you want.
$secret = Get-AzKeyVaultSecret -VaultName joykeyvault -Name mySecret123
$SecurePassword = $secret.SecretValue
$Password = [System.Net.NetworkCredential]::new("", $SecurePassword).Password

ConvertFrom-SecureString -AsPlainText is supported on in PowerShell 7. dont try it on lower version

You can use the -AsPlainText switch on Get-AzKeyVaultSecret.
$secretText = Get-AzKeyVaultSecret -VaultName 'Contoso' -Name 'ITSecret' -AsPlainText
Another option is to add SecretValueText property back to the Microsoft.Azure.Commands.KeyVault.Models.PSKeyVaultSecretIdentityItem objects.
# Update PSKeyVaultSecretIdentityItem object type to include scriptproperty secretvaluetext
$Script = { Get-AzKeyVaultSecret -VaultName $this.VaultName -Name $this.Name -AsPlainText }
Update-TypeData -TypeName 'Microsoft.Azure.Commands.KeyVault.Models.PSKeyVaultSecretIdentityItem' -MemberName 'SecretValueText' -MemberType ScriptProperty -Value $Script
# SecretValueText property will contain decrypted secret text for the session
$secret = Get-AzKeyVaultSecret -VaultName 'Contoso' -Name 'ITSecret'
$secret.SecretValueText

Related

Powershell script won't list expired key vault certificates

I have a powershell script that is attempting to list all the expired secrets of my Azure Key Vault. Unfortunately I'm struggling to do this.
This is how I retrieve sercrets. But what do I need to add to get the expiration of all secrets? Then delete those that are expired? I'm guessing I'll need to set an access policy.
Select-AzSubscription -Subscription "My subscriptsion"
Set-AzKeyVaultAccessPolicy -VaultName "testKeyVaultPwsh" -UserPrincipalName "mystuff#domain.com" -PermissionsToSecrets get,set,delete
#Retrieve secret
$secret = Get-AzKeyVaultSecret -VaultName "testKeyVaultPwsh" -Name "ExamplePassword" -AsPlainText
You can delete the expired secrets using below commands .(Make sure
you have get,set,delete access policies set and given proper
permissions )
I have tried in my environment and able to delete expired secrets sussessfully.
After checking expiry using
$exp =Get-AzKeyVaultSecret -VaultName $vaultname -Name $secretname | Select-Object Name,Expires
$exp
I created secrets and have secrets expired.
Commands:
$vaultname= “<keyvaultname>”
$secrets= Get-AzKeyVaultSecret -VaultName $vaultname
$secretnames =$secrets.Name
$current_date=Get-Date
Foreach($secretname in $secretnames)
{
$exp =Get-AzKeyVaultSecret -VaultName $vaultname -Name $secretname | Select-Object Expires
$keyvaultsecretvexpirydate =[datetime]($exp.Expires)
$timediff=NEW-TIMESPAN -Start $current_date -End $keyvaultsecretvexpirydate
$days_until_expiration=$timediff.Days
Write-Output “days_until_expiration of secret named $secretname is :$days_until_expiration”
Write-Output “ ”
if ($days_until_expiration -eq 0)
{
Write-Output "Secret named $secretname got expired “
Write-Output “removing expired secret : $secretname”
Write-Output “ ”
Remove-AzKeyVaultSecret -VaultName $vaultname -Name $secretname
}
}
Confirm to delete by typing Y and refresh the secrets page to see the expired secret being removed/deleted.
References:
KeyVaultSecretExpirationAlerts |github
remove-azkeyvaultsecret | microsoftdocs

Get-AzKeyVaultSecret can't read secret value in Powershell

I'm not able to read the value of one of my secrets in Key Vault. I'm logged in with my Azure account and I have full permission to the selected Key Vault.
I'm able to retrieve a list of available secrets using the following command:
$keyVaultValue = (Get-AzKeyVaultSecret -VaultName 'name-of-key-vault')
And then see the content when I write:
Write-Output $keyVaultValue
But when I ask for a specific key it just returns null:
$keyVaultValue = (Get-AzKeyVaultSecret -VaultName 'name-of-key-vault' -Name 'my-secret-name').SecretValueText
I've checked the name and subscription ID and everything is correct. I can easily read the value from the portal, but no from powershell on my Windows PC.
Any suggestions?
SecretValueText is deprecated, You can use the following syntax the retrieve the value as plain text:
$keyVaultValue = Get-AzKeyVaultSecret -VaultName 'name-of-key-vault' -Name 'my-secret-name'
$keyVaultValue.SecretValue | ConvertFrom-SecureString -AsPlainText
More information and examples can be found here.
If you want to show all key-vault secrets name and their key values then you can use this in powershell
$secrets=Get-AzKeyVaultSecret -VaultName 'key-vault-name'
$secrets | % {Write-Output "$($_.name) $($(Get-AzKeyVaultSecret -VaultName $_.VaultName -Name $_.Name).SecretValue | ConvertFrom-SecureString -AsPlainText)" }
Try using this function:
function GetSecretValue
{
param(
[String]$keyvaultName,
[String]$secretName
)
Write-Host "Retrieving secret $secretName from $keyvaultName... " -NoNewline
if ((Get-Command Get-AzKeyVaultSecret).ParameterSets.Parameters.Name -contains "AsPlainText")
{
# Newer Get-AzKeyVaultSecret version requires -AsPlainText parameter
$secretValue = Get-AzKeyVaultSecret -VaultName $keyvaultName -Name $secretName -AsPlainText
}
else
{
$secretValue = (Get-AzKeyVaultSecret -VaultName $keyvaultName -Name $secretName).SecretValueText
}
Write-Host "ok"
return $secretValue
}
Usage example:
$keyVaultValue = GetSecretValue "name-of-key-vault" "my-secret-name"

is it possible to update particular value of json using powershell script?

az keyvault secret set --vault-name "" --name "AppSecret" --description "An optional description" --disabled false --value "{`"type`":`"XXXXXX`",`"project_id`":`"XXXXXX`",`"private_key_id`":`"XXXXXXXX`"}"
I have created above secret , is it possible to update particular value of secret using powershell ?
Yes you can set a keyvault secret via Powershell. It will create a new version; however, applications will either automatically get the new version or if referencing a specific version continue to get the same value associated with that version.
$Secret = ConvertTo-SecureString -String 'Password' -AsPlainText -Force
Set-AzKeyVaultSecret -VaultName 'Contoso' -Name 'ITSecret' -SecretValue $Secret
I have developed one simple solution :
If i have json secret like :
{
"Key1" : "123"
"Key2" : "456"
}
and i want to update only key1 then :
1 ) $secret = Get-AzureKeyVaultSecret -vaultname xyz -name abc
2 ) $secretValue = $secret.SecretValueText
3 ) $OldValue = "123"
$NewValue = "456
"
4 ) $secretValue -match $OldValue
$newJson = $secretValue -replace $OldValue,$NewValue
5 )
az keyvault secret set --vault-name "SaurabhD-Test" --name "cvljson" --disabled false
--value $newJson

New-AzADAppCredential Generate Client Secret

Is there a way to generate a password client secret using the New-AzADAppCredential cmdlet? I don't want to supply the password to the cmdlet and would much rather use the generate one much like the Azure Portal.
I am afraid you can't, when using New-AzADAppCredential to create client secret, the -Password is needed.
The workaround is to use the New-AzureADApplicationPasswordCredential command in AzureAD module.
New-AzureADApplicationPasswordCredential -ObjectId "<object-id>"
Not natively, but you can create a very similar client secret using the same tools that generate them in the portal.
It's not as elegant as having the solution baked into the cmdlet, but it works very well.
$bytes = New-Object Byte[] 32
$rand = ([System.Security.Cryptography.RandomNumberGenerator]::Create()).GetBytes($bytes)
$ClientSecret = [System.Convert]::ToBase64String($bytes) | ConvertTo-SecureString -AsPlainText -Force
$endDate = [System.DateTime]::Now.AddYears(1)
New-AzADAppCredential -ObjectId "<object-id>" -Password $ClientSecret -startDate $(get-date) -EndDate $endDate
This is possible now.
$Sub = "Your Sub Here"
Set-AzContext -SubscriptionName $Sub
$app = New-AzADApplication -DisplayName 'MyTestApp'
$secretStartDate = Get-Date
$secretEndDate = $secretStartDate.AddYears(1)
$webApiSecret = New-AzADAppCredential -StartDate $secretStartDate -EndDate $secretEndDate -ApplicationId $app.AppId
Write-Output $webApiSecret
Output:

Azure Authentication With Certificate Setup

I'm trying to set up Azure Key Vault so I can access with a certificate from my PHP application. I'm trying to follow the steps at https://azurecto.com/azure-keyvault-authenticating-with-certificates-and-reading-secrets/, which says you have to create an AD application, but i'm getting error messages. This is what I tried.
A. I already have a self-signed .pfx file on my Windows machine.
B. Because I already have a .pfx file, i change up his steps a bit. I import the .pfx file into the console with
$cert = Get-PfxCertificate -FilePath "C:\azurecrt.pfx"
C. Then it says to create some variables
$vaultName = 'Picklistsca1'
$dnsName = 'picklistsfakeurl.ca'
$dummyUrl = "http://$dnsName/"
D. Then it says call New-AzureRmADApplication. This is where I get into trouble.
$app = New-AzureRmADApplication
-DisplayName $dummyUrl
-HomePage $dummyUrl
-IdentifierUris $dummyUrl
-CertValue $cert
-StartDate '2018-04-07 6:40:23 PM'
-EndDate '2019-04-07 6:40:23 PM'
I get the error message "New-AzureRmADApplication : Cannot convert a primitive value to the expected type 'Edm.Binary'. See the inner exception for more details."
I think this is because the $cert has to be in base64 format, but everything I've tried to convert it to base64 fails. For example I've tried
$bytes = [System.IO.File]::ReadAllBytes("C:\azurecrt.pfx")
$b64 = [System.Convert]::ToBase64String($bytes)
Then replace $cert with $b64 in New-AzureRmADApplication. That gives me the error "New-AzureRmADApplication : Invalid certificate: Key value is invalid certificate"
Any advice would be greatly appreciated. Thanks
I'm trying to set up Azure Key Vault so I can access with a certificate from my PHP application
You could get the answer and demo code from this tutorial.
As juunas mentioned that you need a .cer file.
Following is the snippet from the tutorial
$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certificate.Import('c:\location\certificate.cer') # need a .cer file.
$startDate = $certificate.GetEffectiveDateString()
$endDate = $certificate.GetExpirationDateString()
$credValue = [System.Convert]::ToBase64String($certificate.GetRawCertData())
$azureADApplication = New-AzureRmADApplication -DisplayName "{application name}" -HomePage "{application page}" -IdentifierUris "{application page}" -KeyValue $credValue -KeyType "AsymmetricX509Cert" -KeyUsage "Verify" -StartDate $startDate -EndDate $endDate
Update:
I have updated the code as following. I have tested it on my side.
$credValue = [System.Convert]::ToBase64String($certificate.GetRawCertData())
$azureADApplication = New-AzureRmADApplication -DisplayName "{application name}" -HomePage "{application page}" -IdentifierUris "{application page}" -CertValue $credValue -StartDate $startDate -EndDate $endDate
$azureADApplication.ApplicationId
$principal= New-AzureRmADServicePrincipal -ApplicationId $azureADApplication.ApplicationId

Resources