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

如何用Python结合Microsoft Graph在Azure B2C中自动创建自定义用户流属性

使用Python调用Microsoft Graph创建Azure B2C自定义用户流属性

首先得确保你的Azure AD应用注册已经被授予IdentityUserFlow.ReadWrite.All权限,并且完成了管理员同意,不然调用Graph API会触发权限不足的错误。

你可以基于现有的获取属性代码,添加创建自定义属性的逻辑。下面是完整的实现代码,以创建age这个整数类型的自定义用户流属性为例:

import msal
import requests

# 替换为你的Azure AD B2C配置信息
tenant_id = 'your-tenant-id'
client_id = 'your-client-id'
client_secret = 'your-client-secret'
authority = f'https://login.microsoftonline.com/{tenant_id}'

# 初始化机密客户端应用
app = msal.ConfidentialClientApplication(
    client_id=client_id,
    client_credential=client_secret,
    authority=authority
)

# 获取访问令牌
result = app.acquire_token_for_client(scopes=['https://graph.microsoft.com/.default'])
if 'access_token' not in result:
    print(f"令牌获取失败: {result.get('error_description')}")
    exit()
access_token = result['access_token']

# 构造自定义属性的请求数据
# dataType支持string、int64、boolean、dateTimeOffset几种类型
custom_attribute_payload = {
    "displayName": "年龄",
    "description": "存储用户的年龄信息",
    "userFlowAttributeType": "custom",
    "dataType": "int64",
    "name": "age"
}

# 调用Graph API创建自定义属性
graph_url = "https://graph.microsoft.com/v1.0/identity/userFlowAttributes"
headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
response = requests.post(graph_url, json=custom_attribute_payload, headers=headers)

if response.status_code == 201:
    print("自定义属性创建成功!")
    print(response.json())
else:
    print(f"创建失败: {response.status_code} - {response.text}")

关键细节说明

  • 权限要求:必须给应用注册添加IdentityUserFlow.ReadWrite.All的应用权限,且完成管理员同意,否则会返回403错误。
  • dataType可选值:根据实际需求选择,字符串用string、布尔值用boolean、日期用dateTimeOffset、整数用int64。
  • name字段:这是属性的内部标识,一旦创建就无法修改,需要提前确认好。
  • displayName和description:是在用户流界面显示的名称和描述,用于区分不同属性的用途。

运行代码前记得替换配置中的租户ID、客户端ID和密钥,执行后如果返回201状态码,就说明自定义属性创建成功。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:43:10