【Azure 存储服务】记一次调用Storage Blob API使用 SharedKey Authorization出现的403错误

问题描述

使用Azure Storag Blob REST API上传文件,用SharedKey作为Authorization出现403错误。

错误消息

b'\xef\xbb\xbf<?xml version="1.0" encoding="utf-8"?><Error><Code>AuthenticationFailed</Code><Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.\nRequestId:7df1f139-901e-0063-64eb-4be2dc000000\nTime:2023-03-01T03:08:27.3277224Z</Message><AuthenticationErrorDetail>The MAC signature found in the HTTP request \’' is not the same as any computed signature. Server used following string to sign: 'PUT\n\n\n19122\n\ntext/plain; charset=UTF-8\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:Wed, 01 Mar 2023 03:08:26 GMT\nx-ms-version:2015-02-21\n/adlstestaccount/blobtest/20230220065800824-2696.jpg'.</AuthenticationErrorDetail></Error>' reason=Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.*

问题发现

在错误消息“Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.”中,提到了请求SharedKey 中的内容和请求Header中的内容不一致。

检查生成SharedKey 的代码

第一步:生成put_str

put_str = u"PUT\n\n\n{}\n\n{}; charset={}\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:{}\nx-ms-version:{}\n/{}/{}/{}".format(str(len(file)),
'text/plain' ,
'UTF-8',
get_date(),
'2015-02-21',
'<your storage account name>',
'<container name>',
file_name)

sig_str = base64.b64encode(hmac.new(account_key_decoded, put_str, digestmod=hashlib.sha256).digest()).decode('utf-8')

第二步:请求的Header中,通过Authorization 传递 sig_str

        headers = {
            "x-ms-blob-type": "BlockBlob",
            "x-ms-date": get_date(),
            "x-ms-version": "2015-02-21",
            "Authorization": "SharedKey {}:{}".format("adlstestaccount", sig_str),
            "Content-Type": "{}; charset={}".format('text/plain', 'UTF-8'),
            "Content-Length": str(len(file))
        }

在调试代码的过程中,对比 put_str 内容和 blob服务端 SharedKey信息,发现它们的 x-ms-date 部分值不一样:


image.png

因SharedKey不一样,所以认证时候出现403 Server failed to authenticate the request.

在第一步生成 put_str 的时候获取 x-ms-date 的时候调用的 get_date() 获取时间,第二步在生成Header x-ms-date的时候再一次调用 get_date() 获取时间,由于代码在执行时候出现了时间差,这就导致了header中的时间和Authorization SharedKey中时间不一致。这就是出现403的根本原因。

解决办法就是在获取x-ms-date的时候,不要两次调用get_date()方法,而是只调用一次,然后put_str和header中都使用同一个时间值。

修改后的代码片段为

//获取时间
//获取时间
ms_date = get_date();

put_str = u"PUT\n\n\n{}\n\n{}; charset={}\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:{}\nx-ms-version:{}\n/{}/{}/{}".format(str(len(file)),
'text/plain' ,
'UTF-8',
ms_date,
'2015-02-21',
'<your storage account name>',
'<container name>',
file_name)

sig_str = base64.b64encode(hmac.new(account_key_decoded, put_str, digestmod=hashlib.sha256).digest()).decode('utf-8')


headers = {
            "x-ms-blob-type": "BlockBlob",
            "x-ms-date": ms_date,
            "x-ms-version": "2015-02-21",
            "Authorization": "SharedKey {}:{}".format("adlstestaccount", sig_str),
            "Content-Type": "{}; charset={}".format('text/plain', 'UTF-8'),
            "Content-Length": str(len(file))
        }

附录:使用AAD 和 Storage Account Access Key进行认证获取Blob的Python实例代码

from azure.storage.filedatalake import DataLakeServiceClient
from azure.identity import ClientSecretCredential
from azure.identity import AzureAuthorityHosts

tenant_id = "*"
client_id = "*"
client_secret = "*"
authority = AzureAuthorityHosts.AZURE_CHINA 
credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret,authority=authority) 
account_url = "*"
account_key = "*"
container="*"
folder="*"
connection_string = "*"

def initialize_storage_account():
    try:
        global service_client 
        #使用AAD 认证
        #service_client = DataLakeServiceClient(account_url=account_url, credential=credential)

        #使用Access Key认证
        service_client = DataLakeServiceClient.from_connection_string(connection_string)
    except Exception as e:
         print(e)
         

def list_directory_contents():
    try:
        file_system_client = service_client.get_file_system_client(file_system=container)
        paths = file_system_client.get_paths(path=folder)
        for path in paths:
         print(path.name + '\n')
    except Exception as e:
     print(e)

initialize_storage_account()
list_directory_contents()

参考资料

通过共享密钥进行授权 : https://learn.microsoft.com/zh-cn/rest/api/storageservices/authorize-with-shared-key

Azure Blob 存储和 Python 入门 : https://learn.microsoft.com/zh-cn/azure/storage/blobs/storage-blob-python-get-started?tabs=azure-ad

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355

推荐阅读更多精彩内容