首页 > 其他分享 >【Azure 存储服务】记一次调用Storage Blob API使用 SharedKey Authorization出现的403错误

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

时间:2023-06-29 21:35:17浏览次数:59  
标签:SharedKey Storage client ms API str date Authorization

问题描述

使用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 部分值不一样:

因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

 

 

标签:SharedKey,Storage,client,ms,API,str,date,Authorization
From: https://www.cnblogs.com/lulight/p/17515242.html

相关文章

  • 亚马逊国际获得AMAZON商品详情API接口采集sku商品规格信息列表Java调用演示案例
    ​亚马逊商品详情API接口的作用是获取Lazada电商平台上的某一商品的详情信息,包括商品的名称、销售价格、库存数量、图片、商品描述、品牌、产地、售后保障等信息。开发者可以使用该API接口获取到商品的原始数据,进行分析、筛选等操作。通过该接口获取到的商品详情数据可以结合其......
  • Kubernetes编程——client-go基础—— 深入 API Machinery —— Kind
    深入APIMachinery——Kind 在Kubernetes中,APIMachinery是一个核心的软件库,用于构建Kubernetes的API服务器和控制器。它提供了一些基本的功能,如对象存储、认证鉴权、API请求处理和验证等。 在APIMachinery中,Kind是一个重要的概念。在Kubernetes中,每个资源......
  • 作为用户我该如何调用API 接口获取商品数据
    作为用户,如果你想要获取商品数据,可以通过调用API接口来实现。下面是一些步骤和注意事项,帮助你成功获取商品数据。了解开放平台:首先,你需要了解开放平台,注册一个开发者账号,并创建一个应用。在创建应用时,需要填写一些必要的信息,如应用名称、应用描述等。获取访问权限:在开放平台......
  • C# HttpClient、API访问插件、接口访问
    关于使用插件访问接口.Net版本:NETFramework4.7.2 RestSharp版本:105.2.3.0Post访问 staticstringPostAction(){//公共apiconststringurl="https://api.uomg.com/api/rand.qinghua";//添加api访问......
  • Apifox:在线调试 OpenAI 接口,提供便捷的开发体验
    OpenAI 的API不仅可以通过编程语言(如Python、node.js)进行调用,还可以借助 Apifox 来在线调试。Apifox提供了直观且功能强大的方式来调试OpenAI接口,帮助开发者高效地发现和解决潜在问题。通过利用Apifox,开发者能够更快速地对项目进行迭代优化,确保OpenAI接口的稳定性和可......
  • 在Centos7上部署Yapi
    组件版本:CentOS7Nodev12.22.9mongoDBv4.4.22Yapiv1.12.0一、安装nodenode下载地址:https://registry.npmmirror.com/binary.html?path=node/v12.22.9/下载node压缩包到本地,解压缩文件,移动并重命名node#下载压缩包到本地wgethttps://registry.npmmirror.com/-/bina......
  • api接口接入淘宝/天猫平台采集添加到购物车数据调用演示案例
    ​淘宝添加到购物车API接口的作用是向淘宝购物车中添加指定的商品,实现用户将商品加入购物车的功能。通过该API接口,用户可以将商品加入购物车,方便后续进行结算和购买。使用淘宝添加到购物车API接口,可以帮助开发者和商家进行以下操作:购物车管理:允许用户将商品添加到购物车并进行......
  • P1552 [APIO2012] 派遣 题解
    一、题目描述:给你一个$n$个点的有根树,每个点有两个参数$w$和$v$。再给出一个数$m$。对于每一个点$u$,设它的子树内最多可以选择$k_u$个点$a_1,a_2,...,a_{k_u}$,使得$\sum_{i=1}^kw_{a_i}\lem$。那么点$u$的价值为$v_u\timesk_u$,求$max(\su......
  • 免费体验Stable Diffusion deforum文转视频插件,还有deforum API 接口部署介绍!
    如何使用ServerlessDevs和函数计算快速体验部署StableDiffusion,这个是小白也能简单体验安装部署的教程.有电脑就能操作,依托阿里云原生服务.不用考虑硬件问题本篇主要讲解怎么安装跟部署自定义安装插件跟模型.以deforum文转视频插件举例.deforumapi接口自定义开发镜像定......
  • api接口接入淘宝/天猫平台获取商品销量详情调用演示案例
    ​淘宝商品销量详情接口的作用是获取淘宝平台上某一商品的销售情况信息,包括商品的总销量、近期销量、销售趋势等。通过该接口,可以获取到商品销量的原始数据,用于分析商品的受欢迎程度和市场需求。使用淘宝商品销量详情接口,可以帮助商家和开发者进行以下操作:市场分析:通过获取商......