You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何触发Azure Blob存储的AD令牌过期?慢上传无过期问题咨询

Azure Blob存储AD认证下大文件超时长上传的令牌行为解析

问题场景

想搞清楚单个大文件上传耗时超过90分钟时,Azure Blob存储在AD认证模式下的行为。因为自身网络速度快,磁盘也装不下TB级文件,所以写了模拟慢上传的代码,但即使上传耗时超90分钟,也没出现令牌过期错误,想知道令牌过期会在什么情况下触发。

用户的模拟代码如下:

import os
import time
from io import BufferedReader, FileIO
from azure.identity import ClientSecretCredential
from azure.storage.blob import ContainerClient


class ProgressFile(BufferedReader):
    # For binary opening only

    def __init__(self, filename, read_callback):
        f = FileIO(file=filename, mode='r')
        self._read_callback = read_callback
        super().__init__(raw=f)

        # I prefer Pathlib but this should still support 2.x
        self.length = os.stat(filename).st_size

    def read(self, size=None):
        calc_sz = size
        if not calc_sz:
            calc_sz = self.length - self.tell()
        self._read_callback(position=self.tell(), read_size=calc_sz, total=self.length)
        return super(ProgressFile, self).read(size)

def my_callback(position, read_size, total):
    if position > 0 and position <= 4194304:
       time.sleep(5520)
    print("position: {position}, read_size: {read_size}, total: {total}".format(position=position,
                                                                                read_size=read_size,
                                                                                total=total))


myfile = ProgressFile(filename='./testfile', read_callback=my_callback)

token_credential = ClientSecretCredential(
    # 此处需补充租户ID、客户端ID、客户端密钥
)

container_client = ContainerClient("oauth_url", "containername", token_credential)


def upload(filename):
    blob_client = container_client.get_blob_client("myfile")
    blob_client.upload_blob(myfile, blob_type="BlockBlob")
    print("finish uploading")

upload(int(time.time()))

为什么你的模拟没触发令牌过期

你的代码逻辑存在关键问题:

  • 你在read方法里的sleep是本地读取数据前的等待,这段时间并没有发送任何Azure Blob的上传请求,令牌此时还没被使用。
  • ClientSecretCredential是自动维护令牌生命周期的凭据类,它会在每次请求前检查令牌是否即将过期,如果是,会自动向Azure AD申请新令牌。当你结束sleep开始真正上传时,凭据已经自动刷新了令牌,自然不会触发过期错误。
  • 另外,upload_blob上传BlockBlob时默认采用分块上传(默认块大小4MB),每个块的上传都是独立的HTTP请求,单个请求的持续时间远短于令牌有效期(默认Azure AD令牌有效期60分钟,最长90分钟),单个请求不会占用整个令牌周期。

令牌过期错误的触发条件

只有满足以下场景之一,才会出现令牌过期错误:

  • 手动获取令牌且不刷新:如果不是用ClientSecretCredential这类自动刷新的凭据,而是手动调用get_token获取一次令牌,然后用这个静态令牌创建客户端,上传过程超过令牌有效期后,后续请求就会触发过期错误。
  • 凭据无法自动刷新:比如ClientSecretCredential的配置失效(客户端密钥过期、权限不足、租户ID错误),或者上传过程中网络中断,导致凭据无法连接Azure AD刷新令牌,且现有令牌已经过期。
  • 请求间隔超过令牌有效期:分块上传时,两个块的上传间隔(比如暂停上传后很久再继续)超过令牌有效期,且此时凭据因为某种原因没有自动刷新令牌(比如长时间无请求导致凭据内部的令牌缓存过期,且重新刷新失败)。

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:39:17