Azure graph API 在 Node JS 中创建具有自定义用户属性的 B2C 用户

Azure graph API create B2C user with custom user attribute in Node JS

能否请您帮我使用节点 js 客户端在 Azure AD B2C 中创建一个用户。

在该请求中,我需要填充 "signInNames" 和我在 B2c 中为我的应用程序创建的自定义用户属性。

非常感谢您分享样品请求。

下面的代码使用了Azure Active Directory Authentication Library (ADAL) for Node.js and request packages to interact with the Azure AD Graph API.

1) 获取用于 Azure AD Graph 的访问令牌 API:

const AuthenticationContext = require("adal-node").AuthenticationContext;

const tenant = "myb2cdomain.onmicrosoft.com";
const authority = `https://login.microsoftonline.com/{tenant}`;

const authenticationContext = new AuthenticationContext(authority);

function acquireTokenForApplication(clientId, clientSecret, callback) {
    authenticationContext.acquireTokenWithClientCredentials("https://graph.windows.net/", clientId, clientSecret, function(err, tokenResponse) {
        if (err) {
            callback(err);
            return;
        }

        callback(null, tokenResponse.access_token);
    });
}

2) 创建用户对象:

const userToBeCreated = {
    accountEnabled: true,
    creationType: "LocalAccount",
    displayName: "Alex Wu",
    passwordPolicies: "DisablePasswordExpiration",
    passwordProfile: {
        forceChangePasswordNextLogin: false,
        password: "Test1234"
    },
    signInNames: [
        {
            type: "emailAddress",
            value: "alexw@example.com"
        }
    ],
    "extension_xxx_<customAttributeName>": <customAttributeValue>
};

其中 "xxx" 必须替换为您的 b2c-extensions-app 应用程序的应用程序标识符(不带连字符)。

例如:

"extension_ab603c56068041afb2f6832e2a17e237_SkypeId": "alexw.skype"

3) 发送用户对象到the Azure AD Graph API:

function createUser(tenantId, accessToken, userToBeCreated, callback) {
    request.post({
        url: `https://graph.windows.net/${encodeURIComponent(tenantId)}/users?api-version=1.6`,
        auth: {
            bearer: accessToken
        },
        body: userToBeCreated,
        json: true
    }, (err, response, responseBody) => {
        if (err) {
            callback(err);
            return;
        }

        if (!isSuccessStatusCode(response.statusCode)) {
            const errorResult = responseBody;

            callback({
                code: errorResult["odata.error"].code,
                message: errorResult["odata.error"].message.value
            });

            return;
        }

        const createdUser = responseBody;
        callback(null, createdUser);
    });
}