托管于Static Web App的Angular应用如何获取Azure Storage API调用令牌
解决Azure Static Web App前端获取Azure Storage访问令牌的问题
核心原因
你通过/.auth/me拿到的是AAD的ID令牌,仅用于身份验证,无法直接访问Azure Storage API。要调用Storage接口,需要获取针对Azure Storage资源的委派访问令牌。
步骤1:配置Static Web App的AAD权限
在Azure Portal中操作:
- 找到你的Static Web App,进入“认证”面板,编辑Azure Active Directory提供商。
- 在“权限”部分,点击“添加权限”,搜索并选择“Azure Storage”。
- 添加委派权限下的
user_impersonation(对应Storage Blob数据操作),根据需求选择Storage Blob Data Reader或Storage Blob Data Contributor。 - 保存配置。
步骤2:修改登录请求,指定Storage资源
跳转登录时,在/.auth/login/aad后附加resource参数,指定Storage的资源标识符:
/.auth/login/aad?resource=https://storage.azure.com/
或者用scope参数更精准指定权限范围:
/.auth/login/aad?scope=https://storage.azure.com/user_impersonation
这样登录后,Static Web App会从AAD获取到针对Storage的访问令牌。
步骤3:从/.auth/me中提取访问令牌
此时调用/.auth/me,响应数据中会包含带有access_token字段的身份条目,其aud(受众)值为https://storage.azure.com/。
Angular中提取令牌的示例代码:
async getStorageAccessToken(): Promise<string | null> { const authResponse = await fetch('/.auth/me'); const identities = await authResponse.json(); // 筛选出针对Storage的访问令牌 const storageIdentity = identities.find((id: any) => id.aud === 'https://storage.azure.com/'); return storageIdentity?.access_token || null; }
步骤4:调用Storage Blob API
拿到令牌后,在请求头中携带Authorization: Bearer {token}即可调用Storage接口:
async listContainerBlobs(containerName: string) { const token = await this.getStorageAccessToken(); if (!token) { console.error('未获取到Storage访问令牌'); return; } const apiUrl = `https://myaccount.blob.core.windows.net/${containerName}?restype=container&comp=list`; const response = await fetch(apiUrl, { headers: { 'Authorization': `Bearer ${token}` } }); if (response.ok) { const blobListXml = await response.text(); // 解析XML格式的Blob列表 console.log(blobListXml); } else { console.error('调用Storage API失败', await response.text()); } }
额外注意事项
- 令牌默认有1小时有效期,过期后可调用
/.auth/refresh端点刷新令牌,无需重新登录。 - 确保当前登录用户在Azure Storage账户中被分配了对应的RBAC角色(如Storage Blob Data Reader),否则即使有令牌也会被拒绝访问。
内容的提问来源于stack exchange,提问作者J4N
相关产品推荐
相关产品推荐

