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

如何通过租户ID、应用ID和密码生成Azure Blob SAS URL?

用Azure AD服务主体生成Blob SAS URL的正确方法

你之前依赖存储账户密钥生成SAS的方式不适用于Azure AD服务主体(租户ID/应用ID/密码),需要改用用户委托SAS(User Delegation SAS)——先通过服务主体获取用户委托密钥,再用该密钥签名生成SAS。

核心修改要点

  1. 移除StorageSharedKeyCredential的使用(它依赖账户密钥,而你当前没有该密钥)
  2. 通过BlobServiceClient获取用户委托密钥(由Azure AD身份授权生成,用于SAS签名)
  3. 调用generateBlobSASQueryParameters时,传入用户委托密钥、存储账户名和服务主体应用ID

修改后的完整代码

const {
  BlobServiceClient,
  BlobSASPermissions,
  generateBlobSASQueryParameters,
} = require("@azure/storage-blob");
const { ClientSecretCredential } = require("@azure/identity");

// 初始化Azure AD服务主体凭证
const clientCred = new ClientSecretCredential(
  process.env.STORAGE_TENANT,
  process.env.STORAGE_APPID,
  process.env.STORAGE_PASSWORD
);

// 创建Blob服务客户端
const blobServiceClient = new BlobServiceClient(
  `https://${process.env.STORAGE_ACCOUNT_NAME}.blob.core.windows.net`,
  clientCred
);

async function uploadAndGenerateSAS(image) {
  var blobName = "blobName";
  var containeName = process.env.PROFILE_UPLOAD_CONTAINER_NAME;
  const containerClient = blobServiceClient.getContainerClient(containeName);
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  // 上传图片
  const response = await blockBlobClient.uploadData(image.data, {
    blobHTTPHeaders: {
      blobContentType: image.mimetype,
    },
  });

  if (response.etag) {
    const date = new Date();
    const expires = new Date(
      Date.UTC(
        date.getFullYear() + 2,
        date.getMonth(),
        date.getDate(),
        23,
        59,
        59
      )
    );

    // 获取用户委托密钥
    const userDelegationKey = await blobServiceClient.getUserDelegationKey(
      new Date(), // SAS起始时间(建议指定,增强安全性)
      expires    // SAS过期时间
    );

    // 生成用户委托SAS Token
    const sasToken = generateBlobSASQueryParameters(
      {
        containerName: containeName,
        blobName: blobName,
        startsOn: new Date(),
        expiresOn: expires,
        permissions: BlobSASPermissions.parse("racwd"),
      },
      userDelegationKey,
      process.env.STORAGE_ACCOUNT_NAME,
      process.env.STORAGE_APPID // 服务主体的应用ID(Client ID)
    ).toString();

    const sasUrl = blockBlobClient.url + "?" + sasToken;
    console.log("sasUrl", sasUrl);
    return sasUrl;
  }
}

必要权限说明

你的服务主体需要通过Azure RBAC分配以下权限之一:

  • Storage Blob Data Contributor:包含生成用户委托密钥的权限,适合大多数场景
  • 细粒度权限:Microsoft.Storage/storageAccounts/blobServices/generateUserDelegationKey/action,可单独分配该权限以遵循最小权限原则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:47:05