Azure AD B2C - 如何以编程方式添加自定义属性(扩展 属性)

Azure AD B2C - how to add custom attribute programmatically (extension property)

为了为我的 Azure AD B2C 用户提供一些额外的数据,我想为用户对象(或扩展 属性,我想是同一件事)创建一个新的自定义属性。所以我找到了这个documentation。这是为用户添加自定义属性的正确方法吗?

添加属性的正确方法是通过 'portal.azure.com' 管理门户。

您还需要通过策略创建用户,然后这些属性才能真正对所有用户可用。

另一个要考虑的是扩展名称在每个环境中都会不同,因此您需要一些自定义逻辑来解析从 GraphApi 获得的用户 JSON,并检查以确保该属性以您为该属性指定的名称结尾。

示例:

//Java, sorry
private YourCustomGraphApiUser populateCustomProperty(JsonNode jsonUser) throws JsonProcessingException{

    YourCustomGraphApiUser azureUser = mapper.treeToValue(jsonUser, YourCustomGraphApiUser.class);
    String[] customAttributeNames = new String()["one","two"]; //Replace this with some values from some injected properties
    for(String attributeName : customAttributeNames){
        JsonNode customAttribute = jsonUser.get(attributeName);
        if(customAttribute != null){
            azureUser.set(attributeName, customAttribute.asText());//Assuming custom attributes are stored in a map-like structure in YourCustomGraphApiUser. 
        }
        else{                           
            throw new NotFoundException("Error getting the name for custom attribute "+attributeName, e);
            // OR you could ignore and just log an error. Whatever.
        }           
    }
    return azureUser;
}

您使用 Graph API 在所需的 Application 对象上创建了 extensionProperty。

示例 JSON 请求:

POST https://graph.windows.net/contoso.onmicrosoft.com/applications/269fc2f7-6420-4ea4-be90-9e1f93a87a64/extensionProperties?api-version=1.5 HTTP/1.1
Authorization: Bearer eyJ0eXAiOiJKV1Qi...r6Xh5KVA
Content-Type: application/json
Host: graph.windows.net
Content-Length: 104
{
"name": "skypeId",
"dataType": "String",
"targetObjects": [
    "User"
]

}

如果操作成功,它将 return HTTP 201 Created 状态代码以及完全限定的扩展 属性 名称,可用于将值写入目标类型。 参考:azure-ad-graph-api-directory-schema-extensions