对 Azure 存储表运行查询返回 403 AuthenticationFailed,但返回表中的所有条目返回 200 OK

问题描述

我无法使用 this documentation 查询存储表。

这是我用来获取共享密钥以针对 Azure 存储表进行身份验证的函数

function Get-SharedKeyLiteAuthHeader {
    param(
        [Parameter(Mandatory = $TRUE)]
        [String]
        $StorageAccount,[Parameter(Mandatory = $TRUE)]
        [String]
        $TableName,[Parameter(Mandatory = $TRUE)]
        [String]
        $AccessKey,[Parameter(Mandatory = $FALSE)]
        [String]
        $Version = "2020-04-08"
    )
    $GMTTime = (Get-Date).ToUniversalTime().toString('R')
    $StringToSign = "$GMTTime`n/$($StorageAccount)/$($TableName)"
    $Hmacsha = New-Object System.Security.Cryptography.HMACSHA256
    $Hmacsha.key = [Convert]::FromBase64String($AccessKey)
    $Signature = $Hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($StringToSign))
    $Signature = [Convert]::ToBase64String($Signature)

    return @{
        'x-ms-date'    = $GMTTime
        Authorization  = "SharedKeyLite " + $StorageAccount + ":" + $Signature
        "x-ms-version" = $Version
        Accept         = "application/json;odata=fullMetadata"
    }
}

这是我正在执行的 REST 调用,它返回所有表条目并返回状态代码 200。

$Uri = "https://$($StorageAccount).table.core.windows.net/$($TableName)"
$Headers = Get-SharedKeyLiteAuthHeader -StorageAccount $StorageAccount -TableName $TableName -AccessKey $AccessKey

$AllEntries = Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers -ContentType application/json

这是我正在进行的返回 403 AuthenticationFailed 的 REST 调用

$Uri = "https://$($StorageAccount).table.core.windows.net/$($TableName)()?$top=2"
$Headers = Get-SharedKeyLiteAuthHeader -StorageAccount $StorageAccount -TableName $TableName -AccessKey $AccessKey

$SomeEntries = Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers -ContentType application/json

我的最终目标是 filter by date,但我无法使任何查询参数正常工作。我怀疑这与缺少标题元素有关,但我无法确定这些元素可能是什么,因为 this documentation 讨论了所需的标题元素列出了我已经指定的所有元素。

感谢任何帮助 - 谢谢。

解决方法

尝试更改 URL,只需删除 ()

https://$($StorageAccount).table.core.windows.net/$($TableName)?$top=2

enter image description here


我尝试使用您的代码,它返回 AuthenticationFailed

Invoke-RestMethod : {"odata.error":{"code":"AuthenticationFailed","message":{"lang":"en-US","value":"Server failed to authenticate the request. Make sure the value of Authorization 
header is formed correctly including the signature.

也许您会在收到此错误时更改 StringToSign。但是,它是正确的,不需要添加查询字符串,参见here

查询字符串应包含问号和comp 参数(例如,?comp=metadata)。 没有其他参数应该是 包含在查询字符串中。