Search code examples
azurepowershellcloudazureservicebusazure-servicebus-queues

Unable to connect to service-bus from windows server 2019 using PowerShell


I have the code mentioned below in PowerShell. This code is not working in one of the servers because traffic is not going through the proxy and getting blocked by firewall. Same code is working fine in another server only difference is traffic is automatically getting routed to proxy server.

I have compared the "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings" in working and not working servers have the same values not sure what’s missing why bad server traffic is getting route directly to firewall rather going via proxy

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
Import-Module "C:\\Program Files\\Microsoft Integration Runtime\\5.0\\Gateway\\Microsoft.ServiceBus.dll"
$ConnectionString = "ConnectionString"
$blobPath = "blobPath"
$parentPath = "2047895"
$QueueClient = [Microsoft.ServiceBus.Messaging.TopicClient]::CreateFromConnectionString($ConnectionString)
$String = '{
"EventId": "11111",
"EventType": "SampleReadyForSync",
"EventDescription": "Samples staged sucessfully",
"lob": "lob",
"inputType":"folder",
"source": "'+ $blobPath + "" + $parentPath + '"
}'

$String = $String.Substring(0, [System.Math]::Min(1000, $String.Length))
$Encoding = [system.Text.Encoding]::UTF8
$UTF8String = $Encoding.GetBytes($String)
$MemoryStream = New-Object IO.MemoryStream -ArgumentList $UTF8String, $true
$Message = New-Object Microsoft.ServiceBus.Messaging.BrokeredMessage -ArgumentList $MemoryStream
$Message.MessageId = [Guid]::NewGuid()
$Message.Label = "AC"
$QueueClient.Send($Message)

I have tried forcing proxy as well like below but still no luck and traffic is still going directly to the internet and getting blocked by firewall.

$proxyString = "proxyURL"
$proxyUri = new-object System.Uri($proxyString)
[System.Net.WebRequest]::DefaultWebProxy = new-object System.Net.WebProxy ($proxyUri, $true)
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
 

Tried another option like below

$null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
$ConnectionString = ''
$TokenValidFor = 3600

# This part may need editing, EntityPath is specific to connection strings from policies on a queue level
$Pattern = 'Endpoint=(.+);SharedAccessKeyName=(.+);SharedAccessKey=(.+);EntityPath=(.+)'
([uri]$Endpoint), $PolicyName, $Key, $Queue = ($ConnectionString -replace $Pattern, '$1;$2;$3;$4') -split ';'

$UrlEncodedEndpoint = [System.Web.HttpUtility]::UrlEncode($Endpoint)
$Expiry = [DateTimeOffset]::Now.ToUnixTimeSeconds() + $TokenValidFor
$RawSignatureString = "$UrlEncodedEndpoint`n$Expiry"

$HMAC = New-Object System.Security.Cryptography.HMACSHA256
$HMAC.Key = [Text.Encoding]::ASCII.GetBytes($Key)
$HashBytes = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($RawSignatureString))
$SignatureString = [Convert]::ToBase64String($HashBytes)
$UrlEncodedSignatureString = [System.Web.HttpUtility]::UrlEncode($SignatureString)
$SASToken = "SharedAccessSignature sig=$UrlEncodedSignatureString&se=$Expiry&skn=$PolicyName&sr=$UrlEncodedEndpoint"
$Params = @{
    Uri         = "https://$($Endpoint.Host)/$Queue/messages"
    ContentType = 'text/plain;charset=utf-8'
    Method      = 'Post'
    Body        = 'Hello, World!'
    Headers     = @{
        'Authorization' = $SASToken
    }
}
Invoke-RestMethod @Params 

Works locally fine but from on-premises server getting error like below

Invoke-RestMethod : The remote server returned an error: (500) Internal Server 

Another question I read in some blog that we have to define connectivity mode like below

ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http

But I am not sure how to do it in PowerShell


Solution

  • Issue is fixed by adding connection mode as https. Traffic started via proxy after I specified connection mode and data ingestion started.

    Import-Module "C:\\Program Files\\Microsoft Integration Runtime\\5.0\\Gateway\\Microsoft.ServiceBus.dll"
    $ConnectionString = "ConnectionString"
    $blobPath = "blobPath"
    $parentPath = "2047895"
    **[Microsoft.ServiceBus.ServiceBusEnvironment]::SystemConnectivity.Mode = [Microsoft.ServiceBus.ConnectivityMode]::Https**
    $QueueClient = [Microsoft.ServiceBus.Messaging.TopicClient]::CreateFromConnectionString($ConnectionString)
    $String = '{
    "EventId": "11111",
    "EventType": "SampleReadyForSync",
    "EventDescription": "Samples staged sucessfully",
    "lob": "lob",
    "inputType":"folder",
    "source": "'+ $blobPath + "" + $parentPath + '"
    }'
    
    $String = $String.Substring(0, [System.Math]::Min(1000, $String.Length))
    $Encoding = [system.Text.Encoding]::UTF8
    $UTF8String = $Encoding.GetBytes($String)
    $MemoryStream = New-Object IO.MemoryStream -ArgumentList $UTF8String, $true
    $Message = New-Object Microsoft.ServiceBus.Messaging.BrokeredMessage -ArgumentList $MemoryStream
    $Message.MessageId = [Guid]::NewGuid()
    $Message.Label = "AC"
    $QueueClient.Send($Message)