Steve T
Steve T

Reputation: 1

Undeleting an Azure Blob Using a REST API Call from PowerShell

I am trying to undelete a soft deleted blob from Azure storage, using PowerShell to perform a REST API call.

I used the script below:

# Variables
$storageAccountName = "mystorageAccountName"
$containerName = "mycontainerName"
$blobName = "myblobName"

$resGroup = "myResourceGroup"
$subId = "mySubscriptionID"
$tenantID = "myTenantID"

# Authenticate to your Azure account (interactive login)
Connect-AzAccount -Subscription $subID -TenantId $tenantID

# Get storage account key
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resGroup -AccountName $storageAccountName)[0].Value

# Construct the URL to undelete the blob
$uri = "https://$storageAccountName.blob.core.windows.net/$containerName/"+$blobName+"?comp=undelete"

# Generate current date/time for the x-ms-date header
$date = Get-Date

# Construct the headers
$headers = @{
    "x-ms-date" = $date.ToString("R")
    "x-ms-version" = "2017-04-17"
    "Authorization" = "SharedKey "+$storageAccountName+":"+$storageAccountKey
}

# Invoke the REST API call to undelete the blob
$response = Invoke-RestMethod -Uri $uri -Method POST -Headers $headers

# Output the response
$response

I get the following error (signature obfuscated):

Invoke-RestMethod:
Line |
  30 |  $response = Invoke-RestMethod -Uri $uri -Method Post -Headers $header …
     |              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     |  AuthenticationFailedServer failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:37c8df54-401e-0004-4b5a-7f6f96000000
Time:2024-03-26T08:48:52.3955857ZThe MAC signature found in the HTTP request 'pWOmdziTwlN6KOHkf1P/0wKI9NwKsVky4t40OZfqL+40W6vTs6QXYT1ByMfgXWuicBmTHwfGH==' is not the same as any computed signature. Server used following string to sign: 'POST


application/x-www-form-urlencoded


x-ms-date:Tue, 26 Mar 2024 08:48:53 GMT
x-ms-version:2017-04-17
/<mystorageAccountName>/<mycontainerName>/<myblobName>
comp:undelete'.

I am connecting to Azure, with an account that has Contributor access across the entire subscription.

Upvotes: 0

Views: 77

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136196

The issue is with the authorization header:

"Authorization" = "SharedKey "+$storageAccountName+":"+$storageAccountKey

You cannot pass the account key in the authorization header. You have to compute its value based on the instructions provided here: https://learn.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key.

Upvotes: 0

Related Questions