Create azure secret with get-Credetials in powershell - azure

I am trying to automate VM creation in azure.
I want to prompt users to fill in credentials and then store them in my azure key vault as a secret. the problem is it automatically transfers the password to a secure string thus I can't store the value...

In fact Azure expects you to pass a SecureString to the KeyVault with Set-AzKeyVaultSecret. So you don't need to convert it to plain text.
Set-AzKeyVaultSecret in Docs
# Read in Credentials (Password will be of type SecureString)
$Credential = Get-Credential
# Save password in your key vault
Set-AzKeyVaultSecret -Name "MySecret" -VaultName "MyKeyVaultName" -SecretValue $Credential.Password
And to make it more complete. Here's how you can retrieve it as plain text.
# Plain password
$Credential = Get-Credential
$Credential.GetNetworkCredential().Password

Related

Azure - Access token request with a certificate - postman

i want to test access to key vault using certificate
Scenario
Second case: Access token request with a certificate
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
I am struggling to supply
client_assertion
An assertion (a JSON web token) that you need to create and sign with the certificate you registered as credentials for your application. Read about certificate credentials to learn how to register your certificate and the format of the assertion.
I dont know why powershell has to bes used, and I dont have pfx, so cant use
https://blogs.aaddevsup.xyz/2020/10/how-to-use-postman-to-perform-a-client-credentials-grant-flow-with-a-certificate/
Is it possible to generate signed JWT using postman?
Note: Certificates in postman added. so that part is taken care
I don't think you can generate client_assertion directly in postman, please use the script below to create a self-assigned certificate, then you can use the script you mentioned to get the token.
$certroopath = "C:\Users\Administrator\Desktop"
$certname = "mycert1"
$certpassword = "P#ssw0rd1234"
$cert = New-SelfSignedCertificate -DnsName "$certname" -CertStoreLocation cert:\CurrentUser\My
$pwd = ConvertTo-SecureString -String $certpassword -Force -AsPlainText
$certwithThumb = "cert:\CurrentUser\my\"+$cert.Thumbprint
$filepath = "$certroopath\$certname.pfx"
Export-PfxCertificate -cert $certwithThumb -FilePath $filepath -Password $pwd

Reset the client secret of Azure Service Principal using powershell

Using powershell commands i want to reset the Service Principal client secret.
I followed the below steps from the article https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-5.8.0
but it didnot reset the password
Remove-AzADSpCredential -DisplayName ServicePrincipalName
$newCredential = New-AzADSpCredential -ServicePrincipalName ServicePrincipalName
can you tell what i am doing wrong. I just want to reset the secret and have new one
I executed the above command and then i went to the app registration of that service principal and there i went to certificates & secrets i see it has not createed new secret.
Using bash i am able to reset the password by executing the below command but i want it to be done using powershell command
az ad sp credential reset --name
I went to the app registration of that service principal and there I went to certificates & secrets I see it has not created new secret.
Well, actually the command New-AzADSpCredential did create a new secret for you.
Firstly, you need to know the relationship between App Registration(AD App) and Service principal, see Application and service principal objects in Azure Active Directory.
In short, the service principal is the local representation for the AD App in a specific tenant. When you create the secret for the service principal, it will not appear in the Certificates & secrets blade, you can just get it with Get-AzADSpCredential.
If you want to reset the secret that you can find in the portal, you need to reset the sceret for the AD App(i.e. App Registration) via Remove-AzADAppCredential and New-AzADAppCredential.
You could refer to the sample below, it resets a secret with value ce96a0ed-5ae8-4a5a-9b3c-630da9ea3023, it is valid for one year, you can find it in the portal.
$obj = (Get-AzADApplication -DisplayName joyappv2).ObjectId
Remove-AzADAppCredential -ObjectId $obj -Force
$azurePassword = ConvertTo-SecureString "ce96a0ed-5ae8-4a5a-9b3c-630da9ea3023" -AsPlainText -Force
$date = Get-Date
$newCredential = New-AzADAppCredential -ObjectId $obj -Password $azurePassword -StartDate $date -EndDate $date.AddYears(1)
Note: You could not get the secret value again after creating it, so please store it when creating.

Is there a way to retrieve the client secret of an Azure AD application using PowerShell?

Is there a way to retrieve the Client Secret from Azure AD Application as a plain text by using PowerShell?
I tried with the below commands, but it is returning only the type of the secret, not the actual value.
$objectID = "00000-00000-00000-00000"
$keyID = "00000-00000-00000-00000"
$secret = Get-AzADAppCredential -ObjectId $objectID | Where-Object {$_.KeyId -eq $keyID}
$secret
You cannot retrieve the value of created Client Secret in any way.
Explanation of secretText:
The generated password value is only returned during the initial POST
request to addPassword. There is no way to retrieve this password in
the future.
The only way is add new Client Secret and store the new value securely.
$SecureStringPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force
New-AzADAppCredential -ObjectId 1f89cf81-0146-4f4e-beae-2007d0668416 -Password $SecureStringPassword

How to reference a key-vault secret in a part of the connection string in Azure Functions/apps

I'm setting up the connection string to a service bus in the app settings of an Azure function. Currently, I'm storing the entire connection string in Key Vault and referencing the Key Vault secret in the app settings. That's working fine. But what I'm trying to do without success is to store the Service Bus key only and not the whole connection string in the key vault.
I've tried to concatenate the connection string to the KeyVault reference app settings in the portal as below
Endpoint=sb://xxxxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=#Microsoft.KeyVault(SecretUri=xxxx.vault.azure.net/secrets/yyyy/zzzzz)
But this isn't working.
The reason I need to do this separation, is that I would like to rotate the keys in the key vault, and I can't do that if the whole connection string is stored in the key vault.
UPDATE1:
Splitting the connection string into multiple app setting keys can work for this problem but it would limit my ability to use, let say, service bus triggered azure functions which required the name of the full connection string key in app settings inside the Run method signature as below
public static void Run(
[ServiceBusTrigger("myqueue", AccessRights.Manage, Connection = "ServiceBusConnection")]
string myQueueItem
ILogger log)
UPDATE 2:
The work around I've done so far, which I hope I can do a cleaner approach is to use regex in my automation Powershell to replace only the SharedAccessKey portion of the connection string. This way, I'm only using one app setting for the connection string. It's working, but I'm not comfortable with it.
This is the code I'm using in my Automation Runbook:
$azureAutomationConnectionName = "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -Name $azureAutomationConnectionName
Add-AzureRmAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
$resourceGroupName = 'XXXX'
$serviceBusName = 'XXXX'
$serviceBusAccessPolicyName = 'RootManageSharedAccessKey'
$keyVaultName = 'XXXX'
$keyVaultSecretKey = 'XXXX'
$currentSecret = (Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $keyVaultSecretKey).SecretValueText
# Regenerate the Service Bus Primary Key
New-AzureRmServiceBusKey -ResourceGroupName $resourceGroupName -Namespace $serviceBusName -Name $serviceBusAccessPolicyName -RegenerateKey PrimaryKey
# Get the newly regenerated Primary Key
$newPrimaryKey = (Get-AzureRmServiceBusKey -ResourceGroupName $resourceGroupName -Namespace $serviceBusName -Name $serviceBusAccessPolicyName).PrimaryKey
# The secret is storing the entire connection string. We want to replace the SharedAccessKey Only
$newSecretStr = $currentSecret -replace 'SharedAccessKey=[^;]*', ([string]::Format('SharedAccessKey={0}',$newPrimaryKey))
# Convert the Primary Key to Secure String
$newSecureSecretStr = ConvertTo-SecureString $newSecretStr -AsPlainText -Force
# Update the Secret Value in the Key Vault
Set-AzureKeyVaultSecret -VaultName $keyVaultName -Name $keyVaultSecretKey -SecretValue $newSecureSecretStr
I don't think you can do that, just the app setting with the syntax #Microsoft.KeyVault(...) will be recognized as Key Vault Reference. Otherwise, it just will be recognized as a normal string without the second half in the screenshot.
In your case, the workaround is to store the service bus connection string as two independent app setting, when you use it, splice them together via code.
For example, one is Endpoint=sb://xxxxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=, another one is #Microsoft.KeyVault(SecretUri=xxxx.vault.azure.net/secrets/yyyy/zzzzz). You can also store the first one as a secret in the keyvault, it depends on you.

Access certificate thumprint from Azure DevOps variable group connected to Key vaults

I have a VSTS library variable groups connected to my key-vaults in Azure:
More about it you can read here:
https://learn.microsoft.com/en-us/azure/devops/pipelines/library/variable-groups?view=vsts&tabs=yaml
In key vaults in Azure I have a list of secrets and list of certificates.
Example key vault secrets:
AppInsightsInstrumentationKey
CacheConnectionString
Example certificate:
GlobalCertificate
Now I can access as variables in releasing these variables, by simple syntax:
$(GlobalCertificate)
$(AppInsightsInstrumentationKey)
$(CacheConnectionString)
My goal is to read thumprint of certificate localted in variable $(GlobalCertificate). What's the way to get it?
I know this is old but I found this article searching for the same thing and haven't been able to find a solution elsewhere.
I've been able to sort it out with Powershell but it's bizarre what's required considering we've already uploaded the PFX into the key vault. I also save my pfx passwords into keyvault but if you don't, substitute the variable in the $pwd line with your own value.
In the Azure DevOps Pipeline, create a Powershell task. Script is:
#Convert the Secure password that's presented as plain text back into a secure string
$pwd = ConvertTo-SecureString -String $(GlobalCertificate-Password) -Force -AsPlainText
#Create PFX file from Certificate Variable
New-Item Temp-Certificate.pfx -Value $(GlobalCertificate)
#Import the PFX certificate from the newly created file and password. Read the thumbprint into variable
$Thumbprint = (Import-PfxCertificate -CertStoreLocation Cert:\CurrentUser\My -FilePath Temp-Certificate.pfx -Password $pwd).Thumbprint
Write-Host $Thumbprint
#Rest of Script below or set environment variable for rest of Pipeline
Write-Host "##vso[task.setvariable variable=Thumbprint]$Thumbprint"

Resources