Python使用OData查询Azure存储账户时AuthenticationFailed错误修复方案
解决Azure表存储OData查询AuthenticationFailed错误
问题根源
你的代码存在3个核心问题导致签名验证失败:
- x-ms-date格式错误:Azure要求使用RFC1123格式的UTC时间,而非单纯的年月日字符串
- 签名字符串构造不符合SharedKeyLite规则:缺少HTTP方法、Content-MD5字段,且日期格式不匹配签名要求
- 请求URL格式错误:表名后无需添加
(),直接拼接查询参数即可 - 语法错误:account_name、account_key、table_name的字符串未闭合单引号
修正后的完整代码
import requests import datetime import hmac import base64 from hashlib import sha256 # 修复:补全字符串闭合单引号 account_name = '*****' account_key = '*****' table_name = '*****' # 修复:移除URL中多余的() base_url = f'https://{account_name}.table.core.chinacloudapi.cn/{table_name}' query_url = f"{base_url}?$filter=PropertyName eq 'Value'" # 修复:生成符合要求的RFC1123格式UTC时间 now = datetime.datetime.utcnow() date = now.strftime('%a, %d %b %Y %H:%M:%S GMT') # 构造规范资源路径 canonicalized_resource = f'/{account_name}/{table_name}' # 修复:按照SharedKeyLite规则构造签名字符串 # 格式:HTTP Verb\nContent-MD5\nContent-Type\nDate\nCanonicalizedResource string_to_sign = f'GET\n\napplication/json\n{date}\n{canonicalized_resource}' # 计算签名 signature = base64.b64encode(hmac.new(base64.b64decode(account_key), string_to_sign.encode('utf-8'), sha256).digest()).decode() headers = { 'Accept': 'application/json;odata=nometadata', 'Content-Type': 'application/json', 'x-ms-date': date, 'Authorization': f'SharedKeyLite {account_name}:{signature}' } print(headers) response = requests.get(query_url, headers=headers) if response.status_code == 200: result = response.json() print(result) else: print(response.text)
关键修正点说明
- 时间格式:RFC1123格式示例为
Fri, 02 Jun 2023 14:26:40 GMT,必须使用UTC时间,确保与服务器时间同步 - 签名字符串:GET请求的Content-MD5为空,所以留空;Content-Type必须与请求头一致;必须显式包含HTTP方法(GET)
- URL规范:Azure表存储的查询URL格式为
https://<account>.table.core.chinacloudapi.cn/<table>?<query-params>,无需额外添加() - 语法修复:补全字符串的单引号,避免代码运行时抛出语法异常
内容的提问来源于stack exchange,提问作者Exploit
相关产品推荐
相关产品推荐

