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

如何在基于MSAL-react的React应用中设置Azure AD B2C扩展属性

在React Azure B2C应用中设置/更新自定义扩展属性

Azure B2C的用户自定义属性无法直接通过前端msal.js客户端API修改,必须通过调用Microsoft Graph API完成,具体步骤如下:

1. 配置应用权限

在Azure门户的应用注册中,为你的React应用添加Microsoft Graph的委托权限:

  • 选择User.ReadWrite(允许用户读写自身信息)或Directory.AccessAsUser.All(更全面的用户数据权限)
  • 点击「授予管理员同意」,确保权限生效

2. 获取Graph API访问令牌

使用msal.js获取访问Microsoft Graph的令牌,代码示例:

const { instance } = useMsal();
const activeAccount = instance.getActiveAccount();

const getGraphAccessToken = async () => {
  const request = {
    scopes: ["https://graph.microsoft.com/User.ReadWrite"],
    account: activeAccount
  };
  try {
    // 静默获取令牌
    const response = await instance.acquireTokenSilent(request);
    return response.accessToken;
  } catch (err) {
    // 静默失败则弹窗获取
    const response = await instance.acquireTokenPopup(request);
    return response.accessToken;
  }
};

3. 调用Graph API更新属性

自定义扩展属性的名称格式为extension_{应用注册客户端ID去掉所有横杠}_{属性名},比如你创建的属性是"Partner",应用客户端ID是123e4567-e89b-12d3-a456-426614174000,那么属性名就是extension_123e4567e89b12d3a456426614174000_Partner。

调用PATCH请求更新属性:

const updatePartnerAttribute = async (newPartnerValue) => {
  const token = await getGraphAccessToken();
  // 替换为你的实际属性名
  const customAttributeName = "extension_xxxxxxxxx_Partner";

  try {
    const res = await fetch("https://graph.microsoft.com/v1.0/me", {
      method: "PATCH",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        [customAttributeName]: newPartnerValue
      })
    });

    if (res.ok) {
      console.log("Partner属性更新成功");
      // 刷新令牌以获取更新后的用户信息
      await instance.acquireTokenSilent({
        scopes: ["openid", "profile", "email"],
        account: activeAccount
      });
    } else {
      const errorData = await res.json();
      console.error("更新失败:", errorData);
    }
  } catch (err) {
    console.error("请求异常:", err);
  }
};

关键注意点

  • 必须严格使用extension_xxxx_属性名的格式作为请求中的属性键,不能直接用创建时的"Partner"
  • 确保应用权限已完成管理员同意,否则会返回权限不足的错误
  • 更新后需要重新获取ID令牌,才能在activeAccount.idTokenClaims中看到最新的属性值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:02:30