Search code examples
azure-active-directoryazure-ad-msalazure-management-api

How to log into Azure App with a user from a different tenant?


I have created an app on my Active Directory through 'App Registrations (Preview) and am using Microsoft Authentication Library (MSAL.js) to log into the app. The app will be making API calls with the 'user_impersonation' scope, so I have enabled that in the app.

I also would like users that have not been added to the tenant to be able to log in and use the app, so I set the 'signInAudence' to 'AzureADandPersonalMicrosoftAccount'. If I understand this correctly, this should allow any account, regardless of the tenant it is a member of to sign in.

However, when I make the login request to the app with an account that is not a user in the apps tenant, I get the error message: 'Selected user account does not exist in tenant 'MyTenant' and cannot access the application 'MyApplicationID' in that tenant. The account needs to be added as an external user in the tenant first. Please use a different account.'

I am using the following javascript to make the call:

var applicationConfig = {
    clientID: "MYCLIENTID",
    authority: "https://login.microsoftonline.com/MYTENANTID",
    graphScopes: ["https://management.azure.com/user_impersonation"],
    graphEndpoint: "https://graph.microsoft.com/v1.0/me"
};

var headers = new Headers();

var userAgentApplication = new Msal.UserAgentApplication(applicationConfig.clientID, applicationConfig.authority, tokenReceivedCallback);

function clicked(){
    console.log('clicked');
    userAgentApplication.loginPopup(applicationConfig.graphScopes).then(function (idToken) {
        userAgentApplication.acquireTokenSilent(applicationConfig.graphScopes).then(function (accessToken) {
            var bearer = "Bearer " + accessToken;
            headers.append("Authorization", bearer);
            var options = {
                method: "GET",
                headers: headers
            };
            var endpoint = "https://management.azure.com/subscriptions?api-version=2016-06-01";
            fetch(endpoint, options).then(function (response) {
                var body = response.body;
            });
        }, function (error) {
        });
    }, function (error) {
        //login failure
    });
}

Is there anything I am missing to get this to work or am I misunderstanding the 'AzureADandPersonalMicrosoftAccount' setting?


Solution

  • You have specified your authority as: https://login.microsoftonline.com/MYTENANTID.

    You need to specify it as https://login.microsoftonline.com/organizations/v2.0, this allows any account to log in.

    This allows users from any Azure AD tenant to log in. Note we cannot use common since you want to access Azure APIs.

    If you specify the tenant id, only users from that tenant should be able to log in.