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

如何在Azure静态Web应用中获取access_token以认证Microsoft Graph API?

解决方案:Azure静态Web应用无需额外OAuth流程获取Microsoft Graph用户头像

你可以通过配置Azure静态Web应用(SWA)的内置身份验证机制,直接获取可用于调用Microsoft Graph的access token,无需启动额外授权流程,具体步骤如下:

1. 配置Azure AD应用的Graph权限

  • 在Azure门户中,找到你的SWA对应的Azure AD企业应用(可通过SWA的「认证」设置入口跳转,或在Azure Active Directory的「企业应用」中搜索SWA名称)。
  • 进入该应用的「权限」页面,点击「添加权限」,选择「Microsoft Graph」,再选择「委派权限」,添加User.Read权限(获取用户头像需要此基础权限)。
  • 点击「授予管理员同意」完成权限配置。

2. 配置SWA认证提供者的额外作用域

  • 回到SWA的「认证」设置,选择Azure AD作为认证提供者,编辑其设置。
  • 在「作用域」(Scopes)字段中添加:https://graph.microsoft.com/User.Read
  • 保存设置,SWA会在用户登录时自动请求该作用域的access token。

3. 前端获取Graph Access Token

  • 用户登录后,调用SWA内置的/.auth/me接口,返回的JSON数据中会包含一个access_token字段(对应resource为https://graph.microsoft.com的条目),这就是可用于调用Graph的令牌。

示例代码(前端JS):

async function getGraphAccessToken() {
  const response = await fetch('/.auth/me');
  const data = await response.json();
  const graphToken = data.find(entry => entry.resource === 'https://graph.microsoft.com')?.access_token;
  return graphToken;
}

4. 调用Graph获取用户头像

  • 使用获取到的access token,请求Microsoft Graph的头像接口:
    • 获取默认大小头像:GET https://graph.microsoft.com/v1.0/me/photo/$value
    • 获取指定大小头像(如48x48):GET https://graph.microsoft.com/v1.0/me/photos/48x48/$value

示例代码:

async function getUserProfilePhoto() {
  const token = await getGraphAccessToken();
  const response = await fetch('https://graph.microsoft.com/v1.0/me/photos/48x48/$value', {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  const blob = await response.blob();
  return URL.createObjectURL(blob); // 转换为可用于img标签的URL
}

内容的提问来源于stack exchange,提问作者Thomas Jäckle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:01:19