代码之家  ›  专栏  ›  技术社区  ›  Dinusha

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

  •  4
  • Dinusha  · 技术社区  · 6 年前

    请您帮助我使用node js client在Azure AD B2C中创建一个用户。

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

    如果您分享一份样品请求,我们将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  9
  •   Chris Padgett    6 年前

    以下代码使用 Azure Active Directory Authentication Library (ADAL) for Node.js request 要与之交互的包 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);
        });
    }