Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Could you please help me to create a user in Azure AD B2C using node js client.

In that request, I need to populate "signInNames" and custom user attribute which I create for my application in B2c.

If you share a sample request is much appreciated.

like image 913
Dinusha Avatar asked Mar 06 '23 09:03

Dinusha


1 Answers

The following code uses the Azure Active Directory Authentication Library (ADAL) for Node.js and request packages to interact with the Azure AD Graph API.

1) Acquire an access token for use with the 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) Create a user object:

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

where "xxx" must be replaced with the application identifier (without hyphens) for your b2c-extensions-app application.

E.g.:

"extension_ab603c56068041afb2f6832e2a17e237_SkypeId": "alexw.skype"

3) Send the user object to 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);
    });
}
like image 192
Chris Padgett Avatar answered Mar 08 '23 23:03

Chris Padgett