question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to loop through tenantid's by changing authority url

See original GitHub issue

Please follow the issue template below. Failure to do so will result in a delay in answering your question.

Library

  • msal@1.x.x or @azure/msal@1.x.x

Description

I’ve created a multi tenant App in Azure AD and can use MSAL+Graph API successfully, however I am not attempting to loop through our tenants to collect information, however am unsure of how to do so.

When creating a loop using forEach it doesn’t change authority so the returned data from the first connection is returned each time.

See code:

function config_app(tenantid, callback, apiUrl) {
    var applicationConfig = {
        auth: {
            clientId: "XXXX-XXXX-XXXX-XXXX",
            authority: "https://login.microsoftonline.com/" + tenantid,
            redirectUri: "https://my.redirecturi.com/fake"
        },
        cache: {
            cacheLocation: "sessionStorage",
            storeAuthStateInCookie: false
        }
    };
    var msalInstance = new Msal.UserAgentApplication(applicationConfig);
    callback(tenantid, applicationConfig, msalInstance, callMSGraph, apiUrl);
}
function sign_in(tenantid, applicationConfig, msalInstance, callback, apiUrl) {
    var scopes = {
        scopes: ["Organization.Read.All"],
        loginHint: "my@email.com"
    };
    msalInstance.acquireTokenSilent(scopes).then(response => {
        callback(response.accessToken, graphAPICallback, apiUrl);
    }).catch(err => {
    });
}
function callMSGraph(accessToken, callback, apiUrl) {
    console.log("calling ms graph");
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200)
            callback(JSON.parse(this.responseText));
    }
    xmlHttp.open("GET", "https://graph.microsoft.com/v1.0/" + apiUrl, true);
    xmlHttp.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xmlHttp.send();
}
function graphAPICallback(data) {
    $('#o365res').append(JSON.stringify(data, null, 2));
}
config_app('XXX-XXX-XXX-XXX-XXX', sign_in, 'organization');

Example Loop:

var clients = ['XXX-XXX-XXX-XXX-XXX','YYYY-YYYY-YYYY-YYYY'];
clients.forEach(function(e) {
    config_app(e, sign_in, 'organization');
});

Are there any better ways to be doing is where it actually works?

Thanks

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
kfear27commented, Feb 28, 2020

Just an FYI I found a solution to this.

Functions:

function getData(tenantid,apiUrl) {
    return new Promise(resolve => {
        var applicationConfig = {
            auth: {
                clientId: "AZURE-APP-ID-HERE",
                authority: "https://login.microsoftonline.com/" + tenantid,
                redirectUri: "https://my.redirect.uri/uri"
            },
            cache: {
                cacheLocation: "localStorage",
                storeAuthStateInCookie: false
            }
        };
        var msalInstance = new Msal.UserAgentApplication(applicationConfig);
        var scopes = {
            forceRefresh: true,
            scopes: ["Organization.Read.All"],
            loginHint: "user@email.com"
        };
        msalInstance.acquireTokenSilent(scopes).then(response => {
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var data = JSON.parse(this.responseText);
                    $('#o365res').append(JSON.stringify(data, null, 2));
                    resolve();
                }
            }
            xmlHttp.open("GET", "https://graph.microsoft.com/v1.0/" + apiUrl, true);
            xmlHttp.setRequestHeader('Authorization', 'Bearer ' + response.accessToken);
            xmlHttp.send();
        }).catch(err => { });
    });
}
function getDataChain(clients) {
    const nextClient = clients.shift();
    if (nextClient) {
        return getData(nextClient,'organization').then(_ => getDataChain(clients))
    } else { return Promise.resolve(); }
}

Client ID array & calling the chaining function:

var clients = ['XXX-XXX-XXX-XXX-XXX','YYY-YYY-YYY-YYY-YYY'];
getDataChain(clients).then(_ => console.log("all finished"));
0reactions
jasonnuttercommented, Feb 27, 2020

@kfear27 Not yet, but we’re working on it. I would follow that issues for updates.

Closing as a duplicate.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Looping through tenants using MSAL.js - Stack Overflow
I have attempted to simply change the config of the MSAL connection however this fails and will use the existing authority value every...
Read more >
SharePoint Online: PowerShell to Iterate through All Site ...
This PnP PowerShell script loops through all sites in your SharePoint Online environment and gets you the site URL. #Parameter $AdminSiteURL = " ......
Read more >
URL Not Generating Properly · Issue #641 · tenancy/multi-tenant
When running an artisan job that loops through all web sites - the URL within the results (an email) is set to localhost....
Read more >
Redirect Users - Auth0
Describes how to redirect users to URLs that have not been added to the AllowList.
Read more >
Set up inventory components - Power Platform | Microsoft Learn
Edit the Command Center App > Get M365 Service Messages flow. Update the List serviceAnnouncements from Graph action and change the Authority ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found