1
votes

Has anyone got an example of this?

This page describes the REST API function I'm trying to use: https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-metadata

This page describes the authorization process. Unfortunately it doesn't seem to specify how to form the authorization string that would be suitable for the above API function: https://docs.microsoft.com/en-us/rest/api/storageservices/authentication-for-the-azure-storage-services

Here's what I've tried. I get a 403 "Forbidden" response code:

import base64, datetime, hashlib, hmac, requests

account_name = 'account123'
account_key = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmn=='
queue_name = 'stuff-to-process'

resource = '/{}/{}?comp=metadata'.format(account_name, queue_name)
rfc1123date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
x_headers = 'x-ms-date:' + rfc1123date
string_to_hash = 'GET\n\n\n\n' + x_headers + '\n' + resource
bytes_to_hash = bytes(string_to_hash).encode('utf-8')
decoded_key = base64.b64decode(account_key)
encoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest())

url = 'https://{}.queue.core.windows.net/{}'.format(account_name, queue_name)
headers = {
    'Authorization': 'SharedKeyLite ' + account_name + ':' + encoded_hash,
    'x-ms-date': rfc1123date
}

response = requests.get(url, params={'comp':'metadata'}, headers=headers, timeout=5)
print 'Response code was', response.status_code
1

1 Answers

2
votes

I tried to reproduce the issue, and the error response below has shown the reason via print response.text.

<?xml version="1.0" encoding="utf-8"?>
<Error><Code>AuthenticationFailed</Code>
  <Message>Server failed to authenticate the request. Make sure the value of Authorization h
eader is formed correctly including the signature.
RequestId:927f38e8-0003-0023-76ad-c84979000000
Time:2017-05-09T10:14:33.8632801Z</Message>
  <AuthenticationErrorDetail>Authentication scheme SharedKeyLite is not supported.</AuthenticationErrorDetail>
</Error>

The key is Authentication scheme SharedKeyLite is not supported. So please use SharedKey instead of SharedKeyLite in the request header Authorization of your code, then it works and you can extract the queue length value from the responce header x-ms-approximate-messages-count via response.header["x-ms-approximate-messages-count"]