Multi-tenant (SaaS) Angular single-page application that authenticates users with Azure AD and calls a protected ASP.NET Core web API
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
- Contributing
This sample demonstrates how to develop a multi-tenant, cross-platform application suite comprising of an Angular single-page application (TodoListSPA) calling an ASP.NET Core web API (TodoListAPI) 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
A recording of a Microsoft Identity Platform developer session that covered this topic of developing a multi-tenant app with Azure Active Directory is available at Develop multi-tenant applications with Microsoft identity platform.
In order to grasp the relevant aspects of multi-tenancy covered in the sample, please follow About the code section below.
- TodoListSPA uses MSAL Angular to authenticate a user and obtains an access token from Azure AD in the name of the current 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/appsettings.json |
Authentication configuration parameters. |
SPA/src/app/auth-config.ts |
Authentication configuration parameters. |
- Dotnet Core SDK must be installed to run this sample.
- 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.
Using a command line interface such as VS Code integrated terminal, follow the steps below:
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-Multitenancy/1-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:
- either follow the steps below for manual registration,
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the configuration files.
Expand this section if you want to use this automation:
-
On Windows, run PowerShell and navigate to the root of the cloned directory
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
In PowerShell run:
cd .\AppCreationScripts\ .\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
- Navigate to the Microsoft identity platform for developers App registrations page.
- 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-api. - Under Supported account types, select Accounts in any organizational directory.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Select Save to save your changes.
- 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.
- Click 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 the 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 declare the parameters to expose this app 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, follow the following steps:
- Click
Setnext 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.
- Click
- All APIs have to publish a minimum of one scope for the client's to obtain an access token successfully. To publish a scope, follow the following steps:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
access_as_user. - Select Admins and users options for Who can consent?
- For Admin consent display name type
Access msal-dotnet-api - For Admin consent description type
Allows the app to access msal-dotnet-api as the signed-in user. - For User consent display name type
Access msal-dotnet-api - For User consent description type
Allow the application to access msal-dotnet-api on your behalf. - Keep State as Enabled
- Select the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
Open the project in your IDE (like Visual Studio) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
API\appsettings.jsonfile. - Find the app key
Domainand replace the existing value with your Azure AD tenant name. - Find the app key
ClientIdand replace the existing value with the application ID (clientId) of the msal-dotnet-api application copied from the Azure portal.
- Navigate to the Microsoft identity platform for developers App registrations page.
- 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-spa. - Under Supported account types, select Accounts in any organizational directory.
- In the Redirect URI section, select Single-page application in the combo-box and enter the following redirect URI:
http://localhost:4200.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, 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 API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Click 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-api. - In the Delegated permissions section, select the access_as_user in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Click 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 the User.Read, User.Read.All in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Click the Add a permission button and then,
⚠️ The next step requires you to go back to your msal-dotnet-api registration.
- Now you need to leave the registration for msal-angular-spa and go back to your app registration for msal-dotnet-api.
- From the app's Overview page, select the Manifest section.
- Find the entry for
KnownClientApplications, and add the Application (client) ID of themsal-angular-spaapplication copied from the Azure portal. i.e.KnownClientApplications: [ "your_client_id_for_TodoListSPA" ]
Open the project in your IDE (like Visual Studio) 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
clientIdand replace the existing value with the application ID (clientId) of the msal-angular-spa application copied from the Azure portal. - Find the key
protectedResources.scopesand replace the existing value with scope you created earlier e.g.api://{clientId_of_service_app}/.default.
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
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
Here we discuss some of the more important aspects of multi-tenant applications.
When registering an application with the Microsoft identity platform for developers, you are asked to select which account types your application supports. The options include the following:
| Audience | Single/multi-tenant | Who can sign in |
|---|---|---|
| Accounts in this directory only | Single tenant | All user and guest accounts in your directory can use your application or API. Use this option if your target audience is internal to your organization. |
| Accounts in any Azure AD directory | Multi-tenant | All users and guests with a work or school account from Microsoft can use your application or API. This includes schools and businesses that use Office 365. Use this option if your target audience is business or educational customers. |
| Accounts in any Azure AD directory and personal Microsoft accounts (such as Skype, Xbox, Outlook.com) | Multi-tenant | All users with a work or school, or personal Microsoft account can use your application or API. It includes schools and businesses that use Office 365 as well as personal accounts that are used to sign in to services like Xbox and Skype. Use this option to target the widest set of Microsoft accounts. |
Your MSAL configuration will reflect your choice audience in the authority parameter. For instance, an application that targets accounts in this directory only will have a configuration similar to:
export function MSALInstanceFactory(): IPublicClientApplication {
return new PublicClientApplication({
auth: {
clientId: "<your-client-id>",
authority: "https://login.microsoftonline.com/<your-tenant-id>",
redirectUri: "http://localhost:4200/",
},
});
}On the other hand, 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, they are just multiplexers.
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.
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.
Steps for deleting a service principal differs with respect to whether the principal is in the home tenant of the application or in another tenant. If it is in the home tenant, you will find the entry for the application under the App Registrations blade. If it is another tenant, 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.The screenshot below shows how to access the service principal from a home tenant:
The rest of the process is the same for both cases. 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.
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 user. - Redirect the user to the correct
/adminconsentendpoint (which is why you need thetenantId).
In your app, to send a tenant admin to the /adminconsent endpoint you would construct a URL as explained below:
// Line breaks are for legibility only.
GET https://login.microsoftonline.com/{tenant}/v2.0/adminconsent?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost:4200
&scope=calendars.readThis is demonstrated in the code snippet below:
adminConsent() {
// if you want to work with multiple accounts, add your account selection logic below
let account = this.authService.instance.getAllAccounts()[0];
if (account) {
const state = Math.floor(Math.random() * 90000) + 10000; // state parameter for anti token forgery
const adminConsentUri = "https://login.microsoftonline.com/" +
`${account.tenantId}` + "/v2.0/adminconsent?client_id=" +
`${auth.credentials.clientId}` + "&state=" + `${state}` + "&redirect_uri=" + `${window.location.origin}` +
"&scope=https://graph.microsoft.com/.default";
// redirecting...
window.location.replace(adminConsentUri);
} else {
window.alert('Please sign-in first.')
}
}You can try the /adminconsent endpoint on the "Admin" page of the sample by clicking on the link on the navbar.
Did you notice the scope here is set to
.default, as opposed toUser.Read.All? 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 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 service principal will be provisioned in that tenant.
The main scope of interest in this sample is User.Read.All. This is a MS Graph API scope, and it allows a user to read every user in the tenant. This scope requires a tenant admin to consent.
Remember that the first time you were not able to sign-in with a non-admin account before providing admin consent for that tenant.
To see why this was so, notice, in src/app/app-module.ts, how the MSAL Guard is setup:
export function MSALGuardConfigFactory(): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
authRequest: {
scopes: [...auth.resources.graphApi.resourceScopes],
},
};
}This means that the user will be prompted for consent during sign-in. However, since only an admin can consent to the scope User.Read.All, a non-admin account will simply not be able to login! (unless consented prior by a tenant admin). For best end-user experience, please have the tenant admin consent to your app before a user from the tenant tries to sign-in.
Consider the application suite in this chapter: msal-dotnet-api and msal-angular-spa. From one perspective, they are two different applications (two different projects), each represented with their own app registration on Azure AD, but from another perspective, they really constitute one application together i.e. a todo list application. In practice, an application can have a many such components: one component for the front-end, another for a REST API, another for a database and etc. While these components should have their own separate representation on Azure AD, they should also somehow know one another.
From the perspective of multi-tenancy, the main challenge with such topologies is with providing admin-consent. This is due to the fact that some of their components, such as a web API or a background micro-service, do not have a front-end, and as such, has no user-interaction capability. The solution for this is to allow the user (in this case, an admin-user) to consent to web API at the same time they consent to the front-end application i.e. give a combined consent. In Chapter 1, we have seen that the /.default scope can be used to this effect, allowing you to consent to many different scopes at one step. However, unlike Chapter 1, our application suite here also has a back-end/web API component. But how could the web API know that the consent comes from a recognized front-end application, as opposed to some foreign application? The answer is to use the KnownClientApplications feature.
KnownClientApplications is an attribute in application manifest. It is used for bundling consent if you have a solution that contains two (or more) parts: a client app and a custom web API. If you enter the
appID(clientID) of the client app into this array, the user will only have to consent only once to the client app. Azure AD will know that consenting to the client means implicitly consenting to the web API. It will automatically provision service principals for both the client and web API at the same time. Both the client and the web API app must be registered in the same tenant.
If you remember the last step of the registration for the client app msal-angular-spa, you were instructed to find the KnownClientApplications in application manifest, and add the application ID (client ID) of the msal-angular-spa application KnownClient witApplications: ["your-client-id-for-msal-angular-spa"]. Once you do that, your web API will be able to correctly identify your front-end and the combined consent will be successfully carried out.
Often the user-based consent will be disabled in an Azure AD tenant or your application will be requesting permissions that requires a tenant-admin consent. In these scenarios, your application will need to utilize the /adminconsent endpoint to provision both the msal-angular-spa and the msal-dotnet-api before the users from that tenant are able to sign-in to your app.
When provisioning, you have to take care of the dependency in the topology where the msal-angular-spa is dependent on msal-dotnet-api. So in such a case, you would provision the msal-dotnet-api before the msal-angular-spa.
This application requires an admin-user to consent to scope api://{clientId-of-msal-dotnet-api}/.default in order to provision the msal-dotnet-api web API to a tenant. This means Azure AD will check if admin-consent is provided to the aforementioned scope during the initial sign-in. As such, only a user with admin privileges will be able to sign-in for the first time. After that, any user from that admin's tenant can sign-in and use the application. This allows you to control whether an ordinary users can provision a multi-tenant app into their tenants.
If you would like to change this behavior i.e. allow regular users to sign-in to the app before admin-consent you can modify the app.module.ts as below. Bear in mind, until admin-consent is provided, users won't be able to access the msal-dotnet-api, resulting in bad user experience.
export function MSALGuardConfigFactory(): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
// authRequest: {
// scopes: [...auth.resources.todoListApi.resourceScopes],
// },
};
}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 = { /* a list of IDs... */ };
string tenantId = ((JwtSecurityToken)context.SecurityToken).Claims.FirstOrDefault(x => x.Type == "tid" || x.Type == "http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
if (!allowedTenants.Contains(tenantId))
{
throw new UnauthorizedAccessException("This tenant is not authorized");
}
};
});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 learn more about single and multi-tenant apps, see:
- Permissions and Consent
- Understanding Azure AD Application Consent Experiences
- Understand User and Admin Consent
- 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
To learn more about token validation, see:
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 azure-ad-b2c ms-identity adal msal].
If you find a bug in the sample, raise the issue on GitHub Issues.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
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.











