Skip to content

SAS token generated for EventHub Instance shared access polices using New-AzEventHubAuthorizationRuleSASToken is not usable #20562

Closed
@KiranBabu-Kirando

Description

Description

Created a SAS Token using cmdlet New-AzEventHubAuthorizationRuleSASToken EventHub Instance Shared Access policies. The SasToken when used in Invoke-RestMethod post headers results in "401 Unauthorized"

Sample:
$rule = Get-AzEventHubAuthorizationRule -ResourceGroupName "MyResourceGroupName" -Namespace "MyEventHubNamesapceName" -Name "EventHubInstanceSharedAccessPolicyName" -Eventhub "MyEventHubName"; New-AzEventHubAuthorizationRuleSASToken -AuthorizationRuleId $($rule.Id) -KeyType Primary -ExpiryTime $endTime;

$sasToken = sr=MyEventHubNamesapceName.servicebus.windows.net%2fMyEventHubName&sig=&se=1672767033&skn=Primary

According to the documentation (https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-sas#generate-a-shared-access-signature-token), skn should be the name of the policy, not the name of the key. So Modifiedthe above token to
$sasToken = sr=MyEventHubNamesapceName.servicebus.windows.net%2fMyEventHubName&sig=&se=1672767033&skn=EventHubInstanceSharedAccessPolicyName

Using Sastoken in Rest call.
$method = "POST";
$URI = "https://MyEventHubNamesapceName.servicebus.windows.net/MyEventHubName/messages";

API headers

    $headers = @{
                "Authorization"="SharedAccessSignature$($sasToken)";
                "Content-Type"="application/atom+xml;type=entry;charset=utf-8";
                };
    # execute the Azure REST API
    $x = Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $body;

Result:
Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

+     $x = Invoke-RestMethod -Uri $URI -Method $method -Headers $header ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

What works:
Creating my own token using the code at https://docs.microsoft.com/en-us/rest/api/eventhub/generate-sas-token#powershell works.

Here are some soultions that generate token and make rest calls,
https://social.msdn.microsoft.com/Forums/en-US/9fbd4847-27dd-4145-bedc-223f662ba867/send-data-to-azure-event-hub-using-powershell?forum=azureiothub
https://gist.github.com/kstrauss/96948f08380719c40b8cd1e6f1bc4fc0

The above solution does not work in powershell constarined language mode.

The reason its working is that the token is created using EventHubNamespace Instance Access Polices and the resourceUri is pointing to EventHub Instance.

Multiple issues:

  1. The "skn" in SasToken should be pointing to SharedAcccessPolicy and not "Primary" or "Secondary"
  2. The sastoken generated using EventHub Instance Shared Access policies is failing with "401 Unauthorized" when used in a rest call.

Issue script & Debug output

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

+     $x = Invoke-RestMethod -Uri $URI -Method $method -Headers $header ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Environment data

Name                           Value
----                           -----
PSVersion                      5.1.19041.2364
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.2364
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Module versions

ModuleType Version    Name              ExportedCommands
---------- -------    ----              ----------------
Script     2.2.6      Az.Accounts       {Add-AzEnvironment, Clear-AzContext, Clear-AzDefault, Connect-AzAccount...}
Script     1.3.0      Az.EventGrid      {Get-AzEventGridDomain, Get-AzEventGridDomainKey, Get-AzEventGridDomainTopic, Get-AzEventGridSubscription...}
Script     1.7.1      Az.EventHub       {Add-AzEventHubIPRule, Add-AzEventHubVirtualNetworkRule, Get-AzEventHub, Get-AzEventHubAuthorizationRule...}
Script     1.4.1      Az.ServiceBus     {Add-AzServiceBusIPRule, Add-AzServiceBusVirtualNetworkRule, Complete-AzServiceBusMigration, Get-AzServiceBusAuthoriz...
Script     3.3.0      Az.Storage        {Add-AzRmStorageContainerLegalHold, Add-AzStorageAccountManagementPolicyAction, Add-AzStorageAccountNetworkRule, Clos...

Error output

DEBUG: 4:33:53 PM - ResolveError begin processing with ParameterSet 'AnyErrorParameterSet'.
DEBUG: 4:33:53 PM - using account id '<Redacted>'...
WARNING: Upcoming breaking changes in the cmdlet 'Resolve-AzError' :
The `Resolve-Error` alias will be removed in a future release.  Please change any scripts that use this alias to use `Resolve-AzError` instead.
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. 
   HistoryId: 105 
ErrorCategory     : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
ErrorDetail       : 
InvocationInfo    : {Invoke-RestMethod}
Line              :     $x = Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $body;
Position          : At C:\Users\<Redacted>\Work Folders\Downloads\<Redacted>.ps1:300 char:10
                    +     $x = Invoke-RestMethod -Uri $URI -Method $method -Headers $header ...
                    +          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BoundParameters   : {}
UnboundParameters : 
HistoryId         : 105 Resolve-AzError : Collection was modified; enumeration operation may not execute.
At line:1 char:1
+ Resolve-AzError
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Resolve-AzError], InvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.Errors.ResolveError
DEBUG: AzureQoSEvent: CommandName - Resolve-AzError; IsSuccess - False; Duration - 00:00:00.2775306; Exception - System.InvalidOperationException: Collection was modified; enumera
tion operation may not execute.
   at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
   at System.Linq.Enumerable.<OfTypeIterator>d__95`1.MoveNext()
   at Microsoft.Azure.Commands.Profile.Errors.ResolveError.ExecuteCmdlet()
   at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord();
DEBUG: Finish sending metric.
DEBUG: 4:33:54 PM - ResolveError end processing.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Labels

CXP Attention[Deprecated] The Azure CXP Support Team is responsible for this issue.Event HubsbugThis issue requires a change to an existing behavior in the product in order to be resolved.customer-reported

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions