| page_type | sample | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| description | This sample demonstrates how to integrate an app with Azure AD as a multi-tenant app. This cross-platform application suite comprises of an Angular single-page application (TodoListSPA) authenticating users and calling an ASP.NET Core web API (TodoListAPI) which is also secured with Azure Active Directory (Azure AD). Due to the topology of this application suite (multi-tier, multi-tenant), additional steps are needed for making the apps available to users in other tenants. | ||||||||||||
| languages |
|
||||||||||||
| products |
|
||||||||||||
| urlFragment | spa-msal-angular-multi-tenant | ||||||||||||
| extensions |
|
Integrate an Angular SPA using MSAL Angular to authenticate users with Azure AD and call a protected web API using the multi-tenant integration pattern (SaaS)
- Overview
- Scenario
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Contributing
- Learn More
This sample demonstrates how to integrate an app with Azure AD as a multi-tenant app. This cross-platform application suite comprises of an Angular single-page application (TodoListSPA) authenticating users and calling an ASP.NET Core web API (TodoListAPI) which is also secured with Azure Active Directory (Azure AD). Due to the topology of this application suite (multi-tier, multi-tenant), additional steps are needed for making the apps available to users in other tenants.
When it comes to integrate Azure AD authentication in their apps, developers can choose to configure their app to be either single-tenant or multi-tenant while registering their app in the Azure portal.
Single tenantapps are only available in the tenant they were registered in, also known as their home tenant.Multi-tenantapps are available to users in both their home tenant and other tenants where they are provisioned. Apps that allow users to sign-in using their personal accounts that they use to sign into services like Xbox and Skype are also multi-tenant apps. We will cover provisioning of a multi-tenant app in other tenants using admin-consent
ℹ️ To learn how to integrate an application with Azure AD as a multi-tenant app, consider going through the recorded session: Develop multi-tenant applications with the Microsoft identity platform.
ℹ️ To learn how to integrate a JavaScript Angular application with Azure AD, consider going through the recorded session: Deep dive on using MSAL.js to integrate Angular single-page applications with Azure Active Directory
- TodoListSPA uses MSAL Angular to authenticate a user and obtains an access token from Azure AD for the API on behalf of the authenticated user.
- The access token is then used by the TodoListAPI to authorize the user.
- TodoListAPI uses Microsoft.Identity.Web to protect its endpoint and accept authorized calls.
| File/folder | Description |
|---|---|
API/TodoListAPI/appsettings.json |
Authentication configuration parameters for the web API. |
SPA/src/app/auth-config.ts |
Authentication configuration parameters for the SPA. |
SPA/src/app/consent/consent.component.ts |
Contains logic for granting admin consent. |
- Either Visual Studio or Visual Studio Code and .NET Core SDK
- You would need at least two Azure Active Directory (Azure AD) tenants to successfully run this sample. For more information on how to get an Azure AD tenant, see How to get an Azure AD tenant.
- On each tenant, at least one admin account (:warning: i.e. global admin) and one non-admin/user account should be present for testing purposes.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial.gitor download and extract the repository .zip file.
⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
cd ms-identity-javascript-angular-tutorial
cd 6-AdvancedScenarios\2-call-api-mt/API
dotnet restore dotnet dev-certs https --clean
dotnet dev-certs https --trustFor more information and potential issues, see: HTTPS in .NET Core.
cd ../
cd SPA
npm installThere are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
> :warning: If you have never used **Microsoft Graph PowerShell** before, we recommend you go through the [App Creation Scripts Guide](./AppCreationScripts/AppCreationScripts.md) once to ensure that your environment is prepared correctly for this step.
1. On Windows, run PowerShell as **Administrator** and navigate to the root of the cloned directory
1. In PowerShell run:
```PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
```
1. Run the script to create your Azure AD application and configure the code of the sample application accordingly.
1. For interactive process -in PowerShell, run:
```PowerShell
cd .\AppCreationScripts\
.\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"
```
> Other ways of running the scripts are described in [App Creation Scripts guide](./AppCreationScripts/AppCreationScripts.md). The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
To manually register the apps, as a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Azure AD tenant.
- Navigate to the Azure portal and select the Azure Active Directory service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
msal-dotnet-mt-api. - Under Supported account types, select Accounts in any organizational directory
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs:
- Select the Add a permission button and then:
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select User.Read in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- In the app's registration screen, select the Expose an API blade to the left to open the page where you can publish the permission as an API for which client applications can obtain access tokens for. The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this API. To declare an resource URI(Application ID URI), follow the following steps:
- Select Set next to the Application ID URI to generate a URI that is unique for this app.
- For this sample, accept the proposed Application ID URI (
api://{clientId}) by selecting Save.ℹ️ Read more about Application ID URI at Validation differences by supported account types (signInAudience).
- All APIs must publish a minimum of one scope, also called Delegated Permission, for the client apps to obtain an access token for a user successfully. To publish a scope, follow these steps:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
TodoList.Read. - Select Admins and users options for Who can consent?.
- For Admin consent display name type in TodoList.Read.
- For Admin consent description type in e.g. Allows the app to read the signed-in user's files..
- For User consent display name type in scopeName.
- For User consent description type in eg. Allows the app to read your files..
- Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
Repeat the steps above for another scope named TodoList.ReadWrite
- For Scope name, use
- Select the Manifest blade on the left.
- Set
accessTokenAcceptedVersionproperty to 2. - Select on Save.
- Set
ℹ️ Follow the principle of least privilege when publishing permissions for a web API.
- All APIs should publish a minimum of one App role for applications, also called Application Permission, for the client apps to obtain an access token as themselves, i.e. when they are not signing-in a user. Application permissions are the type of permissions that APIs should publish when they want to enable client applications to successfully authenticate as themselves and not need to sign-in users. To publish an application permission, follow these steps:
- Still on the same app registration, select the App roles blade to the left.
- Select Create app role:
- For Display name, enter a suitable name for your application permission, for instance TodoList.Read.All.
- For Allowed member types, choose Application to ensure other applications can be granted this permission.
- For Value, enter TodoList.Read.All.
- For Description, enter e.g. Allows the app to read the signed-in user's files..
- Select Apply to save your changes.
Repeat the steps above for another app permission named TodoList.ReadWrite.All
- Still on the same app registration, select the Token configuration blade to the left.
- Select Add optional claim:
- Select optional claim type, then choose Access.
- Select the optional claim idtyp.
Indicates token type. This claim is the most accurate way for an API to determine if a token is an app token or an app+user token. This is not issued in tokens issued to users.
- Select the optional claim acct.
Provides user's account status in tenant. If the user is a member of the tenant, the value is 0. If they're a guest, the value is 1.
- Select Add to save your changes.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
API\TodoListAPI\appsettings.jsonfile. - Find the key
Enter the Client ID (aka 'Application ID')and replace the existing value with the application ID (clientId) ofmsal-dotnet-mt-apiapp copied from the Azure portal.
- Navigate to the Azure portal and select the Azure Active Directory service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
msal-angular-mt-spa. - Under Supported account types, select Accounts in any organizational directory
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Single-page application option.
- In the Redirect URI section enter the following redirect URIs:
http://localhost:4200http://localhost:4200/authhttp://localhost:4200/consent-redirect
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URIs:
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs:
- Select the Add a permission button and then:
- Ensure that the My APIs tab is selected.
- In the list of APIs, select the API
msal-dotnet-mt-api. - In the Delegated permissions section, select TodoList.Read, TodoList.ReadWrite in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Select the Add a permission button and then:
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select User.Read in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Still on the same app registration, select the Token configuration blade to the left.
- Select Add optional claim:
- Select optional claim type, then choose Access.
- Select the optional claim acct.
Provides user's account status in tenant. If the user is a member of the tenant, the value is 0. If they're a guest, the value is 1.
- Select Add to save your changes.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
SPA\src\app\auth-config.tsfile. - Find the key
Enter_the_Application_Id_Hereand replace the existing value with the application ID (clientId) ofmsal-angular-spaapp copied from the Azure portal. - Find the key
Enter_the_Web_Api_Application_Id_Hereand replace the existing value with the application ID (clientId) ofmsal-dotnet-mt-apiapp copied from the Azure portal.
- In the Azure portal, navigate to your
msal-dotnet-mt-apiapp registration, and select the Manifest blade. - In the manifest editor, change the
knownClientApplications: []line so that the array contains the Client ID of the client application (msal-angular-mt-spa) as an element of the array.
For instance:
"knownClientApplications": ["ca8dca8d-f828-4f08-82f5-325e1a1c6428"],- Save the changes to the manifest.
Using a command line interface such as VS Code integrated terminal, locate the application directory. Then:
cd ../
cd SPA
npm startIn a separate console window, execute the following commands
cd API/TodoListAPI
dotnet run-
Open your browser and navigate to
http://localhost:4200. -
Sign-in using the button on top-right:
Regular users won't be able to sign-in, until an admin-user provides admin-consent to application permissions.
You can either consent as admin during initial sign-in, or if you miss this step, via the Admin page
- Once admin-consent is provided, users can select the Get my tasks button to access the todo list. When you create a new task, you will also have an option to assign it to any other user from your tenant:
ℹ️ Consider taking a moment to share your experience with us
Expand for troubleshooting info
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory dotnet ms-identity adal msal].
If you find a bug in the sample, raise the issue on GitHub Issues.
To debug the .NET Core web API that comes with this sample, install the C# extension for Visual Studio Code.
Learn more about using .NET Core with Visual Studio Code.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
Here we discuss some of the more important aspects of multi-tenant applications.
To properly test this application, you need at least 2 tenants, and on each tenant, at least 1 administrator and 1 non-administrator account.
Before each test, you should delete your service principal for the tenant you are about to test, in order to remove any previously given consents and start the provisioning process from scratch.
You will find the entry under the Enterprise Applications blade. Read more about these blades in the How and why applications are added to Azure AD.
In the next screen, select Properties and then the Delete button on the upper side.
You have now deleted the service principal for that tenant. Next time, once a user successfully authenticates to your application, a new service principal will be created (i.e. provisioning) in the tenant from which that user belongs to. Note that only a user with admin privileges in a tenant can provision an app into that tenant.
When registering an application with the Microsoft identity platform for developers, you are asked to select which account types your application supports to sign-in with, commonly referred as audience (see: Supported account types). Your MSAL configuration will reflect your choice of audience in the authority parameter. an application that targets accounts in any Azure AD directory will have its authority parameter set to https://login.microsoftonline.com/organizations, while for an application that targets Accounts in any Azure AD directory and personal Microsoft accounts (such as Skype, Xbox, Outlook.com) it will be https://login.microsoftonline.com/common. Here, /organizations and /common are not real tenants, but just multiplexers that will route the request to the relevant tenant:
export function MSALInstanceFactory(): IPublicClientApplication {
return new PublicClientApplication({
auth: {
clientId: "<your-client-id>",
authority: "https://login.microsoftonline.com/organizations",
redirectUri: "http://localhost:4200/",
},
});
}Please note that if you sign-in guest users at the
/common(or/organizations) endpoint, they will be directed to their home tenant for signing-in. So, if your multi-tenant app cares about applying tenant specific conditional access policies, group assignments or app roles to be applied to the guest users, the app should sign-in the guest user on the tenanted endpoint (https://login.microsoftonline.com/{tenantId}) instead of the/commonendpoint.
If organizations or common is used as the tenant, all tokens will be requested from the users' home tenant. However, this may not be the desired outcome. If a user is invited as a guest, the tokens may be from the wrong authority. Setting the authRequest in the MsalInterceptorConfiguration to a method allows you to dynamically change the auth request. For instance, you may set the authority based on the home tenant of the account when using guest users.
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string, Array<string>>();
protectedResourceMap.set("https://graph.microsoft.com/v1.0/me", ["user.read"]);
return {
interactionType: InteractionType.Popup,
protectedResourceMap,
authRequest: (msalService, httpReq, originalAuthRequest) => {
return {
...originalAuthRequest,
authority: `https://login.microsoftonline.com/${originalAuthRequest.account?.tenantId ?? 'organizations'}`
};
}
};
}A service principal of your multi-tenant app is created via one of the following ways:
- When the first user signs-in to your app for the first time in a tenant.
- Manually or programmatically created by a tenant admin using one of the following
- Consent during sign-in:
This method requires the most minimal setup. The only thing needed is that the tenant admin signs-in first and optionally choose to consent on behalf of your organization during the AAD sign-in as shown in the screen below:
- Consent using the
/adminconsentendpoint
This method provides a programmatic control over the consent process. To be able to consent as an admin with this method, there are two steps your application needs to carry out:
- Determine the
tenantIdof the signed-in (admin) user. - Redirect the (admin) user to the correct /adminconsent endpoint. This is demonstrated in onboard.component.ts:
adminConsent() {
const account = this.authService.instance.getActiveAccount()
if (account) {
// available only in HTTPS context
const state = window.crypto.randomUUID(); // state parameter against csrf
/**
* Construct URL for admin consent endpoint. For more information, visit:
* https://docs.microsoft.com/azure/active-directory/develop/v2-admin-consent
*/
const adminConsentUri = "https://login.microsoftonline.com/" +
`${account.tenantId}` + "/v2.0/adminconsent?client_id=" +
`${msalConfig.auth.clientId}` + "&state=" + `${state}` + "&redirect_uri=" + `http://localhost:4200/adminconsent` +
"&scope=" + `${protectedResources.todoListApi.scopes.read[0].split("/TodoList")[0]}/.default`;
// redirect to admin consent endpoint
window.location.replace(adminConsentUri);
}
}Did you notice the scope here is set to
.default? This is a built-in scope for every application that refers to the static list of permissions configured on the application registration. Basically, it bundles all the permissions in one scope. The /.default scope can be used in any OAuth 2.0 flow. Read more aboutscopesusage at Scopes and permissions in the Microsoft Identity Platform.
When redirected to the /adminconsent endpoint, the tenant admin will see:
After you choose an admin account, it will lead to the following prompt:
Once it finishes, your application's service principal will be provisioned in that tenant.
When provisioning, you have to take care of the dependency in the topology if the client app (msal-angular-spa) is dependent on the service app (msal-dotnet-mt-api). For instance, if your client app needs to acquire tokens to call your service app and asks for consent to the necessary scopes during the sign-in stage, you would need to provision the msal-dotnet-mt-api before the msal-angular-spa. As such, only a user with admin privileges would be able to sign-in for the first time in a new tenant. After that, any user from that admin's tenant can sign-in and use the application.
This sample is configured to allow non-admin users to sign-in to the client SPA from any tenant, as it acquire tokens for the service web API at a later stage (i.e. when the user attempts to use the shared todoList after sign-in), which means the service web API can be provisioned later than the client SPA. You can configure this behavior by modifying the scopes of loginRequest object in auth-config.ts.
By marking your application as multi-tenant, your application will be able to sign-in users from any Azure AD tenant out there. Now you would want to restrict the tenants you want to work with. For this, we will now extend token validation to only those Azure AD tenants registered in the application database.
Below, the event handler OnTokenValidated was configured to grab the tenantId from the token claims and check if it has an entry on the records. If it doesn't, an exception is thrown, canceling the authentication. (See: Startup.cs)
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.Events.OnTokenValidated = async context =>
{
string[] allowedTenants = { /* list of tenant IDs to allow */ };
string userTenantId = context?.Principal?.Claims
.FirstOrDefault(x => x.Type == "tid")?.Value;
if (!allowedTenants.Contains(userTenantId))
{
throw new System.Exception("This tenant is not allowed to call this web API");
}
};
});If organizations or common is used as the tenant in MSAL configuration, all tokens will be requested from the users' home tenant. However, this may not be the desired outcome. If a user is invited as a guest, the tokens may be from the wrong authority. To configure which tenant the tokens should be acquired from in a multi-tenant application, please refer to: Dynamic token request
In certain scenarios, you might need to dynamically configure MSAL application object on the fly. To learn how to do so, please refer to: Dynamic configurations using Factory Providers and APP_INITIALIZER
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
- Microsoft identity platform (Azure Active Directory for developers)
- Azure AD code samples
- Overview of Microsoft Authentication Library (MSAL)
- Register an application with the Microsoft identity platform
- Configure a client application to access web APIs
- Converting an application to Multi-tenant
- Multi-tenant SaaS database tenancy patterns
- How to configure a new multi-tenant application
- How to: Sign in any Azure Active Directory user using the multi-tenant application pattern
- Add a multitenant application to the Azure AD application gallery
- Permissions and Consent
- Understanding Azure AD application consent experiences
- Understand user and admin consent
- Application and service principal objects in Azure Active Directory
- Authentication Scenarios for Azure AD
- Building Zero Trust ready apps
- National Clouds
- Microsoft.Identity.Web
- Validating Access Tokens
- User and application tokens
- Validation differences by supported account types
- How to manually validate a JWT access token using the Microsoft identity platform










