Adding a websocket operation in APIM with powershell at root level - powershell

I am trying to import a Websocket Api through Az scripts.
As described in Microsoft doc here, this api contains a method onHandshake at root level.
$operationDst = New-AzApiManagementOperation
-Context $apimDstContext
-ApiId $fullApiId
-ApiRevision $api.ApiRevision
-Name $operation.Name
-OperationId $operation.OperationId
-Method $operation.Method
-Description $opDescription
-UrlTemplate $urlTemplate
-Request $requestDst
-Responses $responsesDst
-Debug -Verbose -ErrorAction Break;
Problem is when importing this method the -urltemplate param value is "" and I keep receiving this error :
System.Management.Automation.ParameterBindingValidationException: Cannot validate argument on parameter 'UrlTemplate'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
I tried setting it to $null for no better and "/" which then gives me this error :
"Operation entity cannot be defined by user for web socket api type."

Actually the onHandshake method is automatically added when creating a Websocket Api.
So I should just ignore the import of that method

Related

Azure AD - Cannot set Application Registration Key Credential with Type "Sign"

I'm trying to set a custom signing key for an Azure AD Application Registration. However, I get a confusing error message and cannot complete the request.
I tried to set the credential using multiple strategies:
PowerShell New-AzureADApplicationKeyCredential command
Microsoft Graph API
Manipulating the Application Registrations Manifest directly in Azure Portal
Microsoft Graph returns a simple "Bad Request", whereas PowerShell and Azure Portal are more specific in their responses:
"The value for the property "usage" in one of your credentials is invalid. Acceptable values are Sign, Verify."
The interesting thing about this error is that I am specifying the usage as "Sign".
PowerShell code snippet:
$appObjectID = $appRegistration.ObjectId
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cer.Import("<path-to-certificate>")
$bin = $cer.GetRawCertData()
$base64Value = [System.Convert]::ToBase64String($bin)
$bin = $cer.GetCertHash()
$base64Thumbprint = [System.Convert]::ToBase64String($bin)
New-AzureADApplicationKeyCredential `
-ObjectId $appObjectID `
-CustomKeyIdentifier $base64Thumbprint `
-Type AsymmetricX509Cert `
-Usage Sign `
-Value $base64Value `
-StartDate $cer.GetEffectiveDateString() `
-EndDate $cer.NotAfter.ToString()
Error message:
Code: Request_BadRequest
Message: The value for the property "usage" in one of your credentials is invalid. Acceptable values are Sign, Verify.
RequestId: <id>
DateTimeStamp: <timestamp>
Details: PropertyName - keyCredentials.keyId, PropertyErrorCode - InvalidKeyUsage
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed`
This is based on the documentation: MS Docs: New-AzureADApplicationKeyCredential. However, I think there is a mistake in this documentation, since they use a randomly generated GUID as input for the parameter ObjectID, which should be the ObjectID of the Application Registration I want to add the new key credential to. So I replaced this keyId with the ObjectId of my Application Registration. (If I directly use the code from MS Docs, I get a "Request_ResourceNotFound" error because the command can't find the Application Registration with this random GUID in Azure AD.)
Things I have tried:
Change -Usage Sign to -Usage "Sign"
Adding a "Verify" credential to the App (works as expected) with this command
When I try to directly modify the Manifest in Azure Portal, I basically get the same error message:
Failed to update <app-name> application. Error detail: The value for the property "usage" in one of your credentials is invalid. Acceptable values are Sign, Verify.
Screenshot from error in Azure Portal
Is there maybe a issue that some parameters cannot be used this way when setting a "Sign" credential?
Thanks in advance for any help and regards!
Thanks to Ash (see his comment to my initial question) I found the solution in this article. I followed the tutorial and could set the "Sign" Key Credential using Graph API after also including a "Verify" Key Credential and a corresponding Password Credential into the request body.

Get-WSManInstance ignores -ErrorAction parameter

Consider the following script:
$ErrorActionPreference = "SilentlyContinue"
$selectorset = #{
Transport = "HTTPS"
Address = "*"
}
$listener = Get-WSManInstance -ErrorAction Stop `
-ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset
write "Bye!"
For the case when the HTTPS listener is absent, the Get-WSManInstance invocation throws a "cannot find the resource" error (and this is expected). However, this invocation seems to only respect the value of $ErrorActionPreference and completely ignore the value of the -ErrorAction parameter (which is supposed to override the value of $ErrorActionPreference), you may try different combinations of the supported values for these two settings. I have tested the behavior with PowerShell versions 5.1.17763.1490 and 4.0.
If I get it right, the error in this case is a "non-terminating error", otherwise $ErrorActionPreference would have been ignored too.
In contrast, when I test the -ErrorAction parameter with some standard cmdlets like Write-Error or Get-Item, it seems to work as expected.
I am quite new to PowerShell and trying to understand if I am missing something here or it is a bug with Get-WSManInstance (or maybe there are some implementation specifics to this particular cmdlet).

How to use Get-AzKeyVaultSecret in Powershell Azure Function 2.x

I'm setting up a Powershell Azure Function that needs keys from an Azure KeyVault. Most of the keys can be retrieved by using the #Microsoft.KeyVault(SecretUri='MySecretUriWithVersion') method.
One of the keys changes frequently. Hence the SecretUri cannot be used.
All keys are stored in the same KeyVault and the Function has a MSI that can read, list and change all keys.
I'm working with a refresh token that needs to be updated. This value is renewed every time my code runs and needs to be updated in the keyvault
Connect-AzAccount -Identity
#Works
Get-AzKeyVault -VaultName $VaultName -ResourceGroupName $rgName
#Not working
Get-AzKeyVaultSecret -VaultName $VaultName -Name $KeyName
Expected output: The code retrieves the key.
Actual output: ERROR: Operation returned an invalid status code
'Unauthorized' Microsoft.Azure.WebJobs.Script.Rpc.RpcException :
Result: ERROR: Operation returned an invalid status code
'Unauthorized' Exception: Operation returned an invalid status code
'Unauthorized' Stack: at
Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretWithHttpMessagesAsync(String
vaultBaseUrl, String secretName, String secretVersion, Dictionary`2
customHeaders, CancellationToken cancellationToken)
dlet.ProcessRecord()
Taken from Microsoft: https://learn.microsoft.com/en-us/azure/key-vault/quick-create-powershell
Have you tried dot notation on retrieving those keys?
(Get-AzKeyVaultSecret -vaultName $VaultName -name $KeyName).SecretValueText
If that doesn't work, you may look at this github issue regarding ManagedAppServices: https://github.com/Azure/azure-powershell/issues/8983
Seems to be the same issue you're having.
There is now a new method for this.
$secret = Get-AzKeyVaultSecret -VaultName "<your-unique-keyvault-name>" -Name "ExamplePassword"
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue)
try {
$secretValueText = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
} finally {
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
}
Write-Output $secretValueText
Refer to: https://learn.microsoft.com/en-us/azure/key-vault/secrets/quick-create-powershell
The original error is fixed in Azure Functions now.
It is still necessary to retrieve keys that are updated frequently in key vault. To do that, I use this:
(Get-AzKeyVaultSecret MyVaultName -Name MySecretName).secretvalue | ConvertFrom-SecureString -AsPlainText
Also, please refer to this link if you face any issues due to secretValueText being deprecated.

AzureRmApiManagementContext: FormatException when used as parameter in cmdlet

I am trying to use some of the Azure Powershell cmdlets in the AzureRM.ApiManagement module. A lot of the cmdlets require a context parameter, which is PsApiManagementContext object.
Following the guidance I have created a context using the New-AzureRmApiManagementContext cmdlet:
$ApiMgmtContext = New-AzureRmApiManagementContext
-ResourceGroupName "MyResourceGroup"
-ServiceName "MyApimService"
I then pass the context as a parameter to the cmdlet:
Get-AzureRmApiManagementUser -Context $ApiMgmtContext
The problem is that I get an error back as follows:
Get-AzureRmApiManagementUser : FormatException: One more parameters were not formatted correctly
I have used Fiddler to inspect the request that it generates and I can see that the body of the request is empty, so there must be something wrong with the way the context object has been created, even though I have basically copied the example in the microsoft docs. I have logged into my Azure subscription using Login-AzureRmAccount and selected the correct subscription prior to trying to create the context.
What am I doing wrong in the creation of the context object?

Create Vm in WAP using PowerShell, error 400

I'm trying to create a VM using PowerShell in Windows Azure Pack.
I've downloaded the subscription, and Get-WAPackVM returns the VM's already created.
I've tried running these two scripts:
$OSDisk = Get-WAPackVMOSDisk -Name "W2012R2 Template_disk_1"
$SizeProfile = Get-WAPackVMSizeProfile -Name "Template"
New-WAPackVM -Name "ContosoV073" -OSDisk $OSDisk -VMSizeProfile $SizeProfile
and
$Credentials = Get-Credential
$Template = Get-WAPackVMTemplate -Name "Template 1"
New-WAPackVM -Name "VirShits7" -Template $Template -VMCredential $Credentials -Windows
Both returns the same error:
New-WAPackVM : The remote server returned an error: (400) Bad Request.
All the Get cmdlets return values, and seem to be correct.
Anyone know how I get this to work?
You may reference the page:
https://msdn.microsoft.com/en-us/library/jj643289.aspx
The page say:
The key properties that you must set on the virtual machine object that is used with the Service Provider Foundation service are as follows: CloudId, StampId, VMTemplateId ,Name.
You may need to assign CloudId and StampId.
I did it by RESTApi and it works.