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

Chrome扩展中用MSAL+Azure AD通过chrome.identity获取用户数据遇401问题

解决Chrome扩展调用Microsoft Graph API 401未授权问题

核心问题分析

你遇到的401错误本质是获取的访问令牌没有Microsoft Graph API的访问权限,同时存在权限配置、令牌请求逻辑的问题,具体修复步骤如下:

具体修复步骤

1. 修正授权请求的权限范围(Scope)

调用https://graph.microsoft.com/v1.0/me需要User.Read权限,你当前的授权请求只包含了Azure管理API的权限,需添加Graph API的权限:

修改authProvider.js中的authUrl的scope参数:

const authUrl =
  "https://login.microsoftonline.com/" +
  tenant_id +
  "/oauth2/v2.0/authorize?" +
  "response_type=token" +
  "&response_mode=fragment" +
  "&prompt=login" +
  "&client_id=" +
  client_id +
  "&redirect_uri=" +
  redirectUrl +
  "&scope=openid profile https://graph.microsoft.com/User.Read"; // 替换为Graph所需权限

2. 更新Manifest的OAuth2配置

同步修改manifest.json中的oauth2.scopes,添加Graph API权限:

"oauth2": {
  "client_id": "1f580835-************-8943****7ee",
  "scopes": ["openid", "email", "profile", "https://graph.microsoft.com/User.Read"],
  "redirect_uri": "chrome-extension://hneoplch****************mkod/index.html"
}

3. 在Azure AD应用注册中配置并授予Graph API权限

  • 登录Azure门户,找到你的应用注册
  • 进入API权限页面,点击添加权限,选择Microsoft Graph
  • 选择委托权限,搜索并添加User.Read权限
  • 点击授予管理员同意(企业租户应用需管理员操作;个人账号登录时需用户手动同意)

4. 优化令牌提取逻辑(避免正则潜在问题)

当前用正则提取令牌的方式可能在特殊场景下失效,改用更可靠的URL片段解析:

// 替换原token提取代码
const urlParams = new URLSearchParams(responseWithToken.split('#')[1]);
const token = urlParams.get('access_token');

5. 统一登录/登出逻辑(避免MSAL与chrome.identity混用冲突)

你当前登录用chrome.identity.launchWebAuthFlow,登出却用MSAL的instance.logout(),会导致状态不一致。建议统一逻辑:

export const useSignOut = () => {
  const signOut = async () => {
    // 清除本地存储的令牌
    await chrome.storage.local.remove('azure_token');
    // 跳转到Azure登出页面
    chrome.identity.launchWebAuthFlow({
      url: `https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/logout?post_logout_redirect_uri=${encodeURIComponent(chrome.identity.getRedirectURL())}`,
      interactive: true
    }, () => {
      console.log("Logged out");
    });
  };
  return signOut;
};

6. 验证令牌有效性(可选)

可以使用本地JWT解析工具解析获取的令牌,检查aud(受众)是否为https://graph.microsoft.com,scp(权限)是否包含User.Read,以此确认令牌是否正确。

测试验证

修改完成后,重新加载Chrome扩展,登录后再次调用getUserData,应该能正常获取用户信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:33:18