azurepowershellazureservicebussas-token

Azure Service Bus Send Message - Invalid authorization token signature


I have the below powershell code to send a message to Azure Service Bus Queue.

param
(
    [Parameter(Mandatory = $true)][string] $ResourceGroupName,
    [Parameter(Mandatory = $true)][string] $NamespaceName,
    [Parameter(Mandatory = $true)][string] $QueueName,
    [Parameter(Mandatory = $false)][string] $PolicyName = 'SASPolicy'
)      
$test_msg = [PSCustomObject] @{ "test" = "This is a test message" } | ConvertTo-Json -Compress
$authorizationId = (Get-AzServiceBusAuthorizationRule -ResourceGroupName $ResourceGroupName -NamespaceName $NamespaceName -QueueName $QueueName).Id
$token = (New-AzServiceBusAuthorizationRuleSASToken -AuthorizationRuleId $authorizationId  -KeyType PrimaryKey -ExpiryTime Get-Date.AddHours(1.0)).SharedAccessSignature 

$auth_headers = @{ "Authorization" = "SharedAccessSignature $token"; "Content-Type" = "application/json" }
$uri = "https://$NamespaceName.servicebus.windows.net/$QueueName/messages"
$http_statuscode = Invoke-WebRequest -Uri $uri -Headers $auth_headers -Method Post -Body $test_msg
Write-Host "Message sent successfully: $http_statuscode.StatusCode"

I am getting the below error for on the invoke-webrequest

Response status code does not indicate success: 401 (SubCode=40103: | Invalid authorization token signature).


Solution

  • I had the wrong Policy Name i.e. PrimaryKey should be replaced by the 'SASPolicy' which is the name of the SAS policy defined on the bus.

    $token = (New-AzServiceBusAuthorizationRuleSASToken -AuthorizationRuleId $authorizationId  -KeyType PrimaryKey -ExpiryTime Get-Date.AddHours(1.0)).SharedAccessSignature 
    

    To

    $token = (New-AzServiceBusAuthorizationRuleSASToken -AuthorizationRuleId $authorizationId  -KeyType SASPolicy -ExpiryTime (Get-Date).AddHours(1.0)).SharedAccessSignature