page_type | extensions | languages | products | urlFragment | description | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
|
|
|
spa-msal-angular-netcore |
This sample demonstrates an Angular single-page application (SPA) to sign-in users and call a ASP.NET Core web API secured with Azure Active Directory (Azure AD) using the Microsoft Authentication Library for Angular (MSAL Angular) for the SPA and the Microsoft.Identity.Web (MIW) for the web API. |
Angular single-page application using MSAL Angular to sign-in users with Azure Active Directory and call a .NET Core web API
- Overview
- Scenario
- Contents
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Contributing
- Learn More
This sample demonstrates an Angular single-page application (SPA) to sign-in users and call a ASP.NET Core web API secured with Azure Active Directory (Azure AD) using the Microsoft Authentication Library for Angular (MSAL Angular) for the SPA and the Microsoft.Identity.Web (MIW) for the web API.
ℹ️ See the community call: Implement authorization in your applications with the Microsoft identity platform
- The client Angular SPA uses MSAL Angular to sign-in and obtain a JWT access token from Azure AD.
- The access token is used as a bearer token to authorize the user to call the .NET Core web API protected by Azure AD.
- The web API responds with the currently signed-in user's todolist.
File/folder | Description |
---|---|
SPA/src/app/auth-config.ts |
Authentication parameters for SPA project reside here. |
SPA/src/app/app.module.ts |
MSAL Angular is initialized here. |
API/TodoListAPI/appsettings.json |
Authentication parameters for API project reside here. |
API/TodoListAPI/Startup.cs |
Microsoft.Identity.Web is initialized here. |
API/TodoListAPI/Controllers/TodoListController.cs |
Contains logic for controlling access to data. |
- Either Visual Studio or Visual Studio Code and .NET Core SDK
- An Azure AD tenant. For more information, see: How to get an Azure AD tenant
- A user account in your Azure AD tenant. This sample will not work with a personal Microsoft account. If you're signed in to the Azure portal with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial.git
or 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 3-Authorization-II/1-call-api/API/TodoListAPI
dotnet restore
The .NET Core project runs on HTTPS. You might need to trust the development certificates if this is your first time running a project. To do so, execute the following from your shell or command line:
dotnet dev-certs https --clean
dotnet dev-certs https --trust
For more information and potential issues, see: HTTPS in .NET Core.
cd ../
cd SPA
npm install
There 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:
⚠️ If you have never used Microsoft Graph PowerShell before, we recommend you go through the App Creation Scripts Guide once to ensure that your environment is prepared correctly for this step.-
On Windows, run PowerShell as Administrator 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.
-
For interactive process -in PowerShell, run:
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. 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-api
. - Under Supported account types, select Accounts in this organizational directory only
- 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 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's 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, enter TodoList.Read (case-sensitive).
- Select Admins and users options for Who can consent?.
- For Admin consent display name type in the details,
e.g. Allow the users of the app msal-dotnet-api to read Todolist items
. - For Admin consent description type in the details
e.g. Allows the app msal-dotnet-api to read the signed-in users Todolist items.
- For User consent display name type in the details
e.g. Read Todolist items as yourself
. - For User consent description type in the details
e.g. Allow the app msal-dotnet-api to read Todolist items on your behalf.
- 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
- Select the Manifest blade on the left.
- Set
accessTokenAcceptedVersion
property to 2. - Select on Save.
- Set
ℹ️ Follow the principle of least privilege whenever you are publishing permissions for a web API.
- All APIs should publish a minimum of one App role, 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 (case-sensitive).
- For Description, enter Allow this application to read every users Todo list items.
- Select Apply to save your changes.
Repeat the steps above for another app permission named TodoList.ReadWrite.All
ℹ️ See how to use application permissions in a client app here: .NET Core daemon console application calling a protected web API with its own identity.
- 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.
- 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.json
file. - Find the key
Enter the domain of your Azure AD tenant, e.g. 'contoso.onmicrosoft.com'
and replace the existing value with your Azure AD tenant name. - Find the key
Enter the Client ID (aka 'Application ID')
and replace the existing value with the application ID (clientId) ofmsal-dotnet-api
app copied from the Azure portal. - Find the key
Enter the tenant ID
and replace the existing value with your Azure AD tenant ID.
- 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-spa
. - Under Supported account types, select Accounts in this organizational directory only
- 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:4200/
http://localhost:4200/auth
- 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-api
. - In the Delegated permissions section, select the TodoList.Read, TodoList.ReadWrite in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
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.ts
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofmsal-angular-spa
app copied from the Azure portal. - Find the key
Enter_the_Tenant_Info_Here
and replace the existing value with your Azure AD tenant ID. - Find the key
Enter_the_Web_Api_Application_Id_Here
and replace the existing value(s) with the application ID (client ID) of the web API project that you've registered earlier, e.g.api://<msal-dotnet-api-client-id>/TodoList.Read
From your shell or command line, execute the following commands:
cd 3-Authorization-II\1-call-api\API
dotnet run
Then, open a separate command line and run:
cd 3-Authorization-II\1-call-api\SPA
npm start
- Open your browser and navigate to
http://localhost:4200
. - Select the Sign In button on the top right corner.
- Select the TodoList button on the navigation bar. This will make a call to the TodoList web API.
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
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
angular
ms-identity
adal
msal
].
If you find a bug in the sample, raise the issue on GitHub Issues.
You need to set cross-origin resource sharing (CORS) policy to be able to call the TodoListAPI in Startup.cs. For the purpose of the sample, CORS is enabled for all domains and methods. This is insecure and only used for demonstration purposes here. In production, you should modify this as to allow only the domains that you designate. If your web API is going to be hosted on Azure App Service, we recommend configuring CORS on the App Service itself.
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}
On the web API side, the AddMicrosoftIdentityWebApiAuthentication
method in Startup.cs protects the web API by validating access tokens sent tho this API. Check out Protected web API: Code configuration which explains the inner workings of this method in more detail. Simply add the following line under the ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
// Adds Microsoft Identity platform (AAD v2.0) support to protect this Api
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
// ...
}
For validation and debugging purposes, developers can decode JWTs (JSON Web Tokens) using jwt.ms.
Access tokens that have neither the scp (for delegated permissions) nor roles (for application permissions) claim with the required scopes/permissions should not be accepted. In the sample, this is illustrated via the RequiredScopeOrAppPermission
attribute in TodoListController.cs:
[HttpGet]
/// <summary>
/// An access token issued by Azure AD will have at least one of the two claims. Access tokens
/// issued to a user will have the 'scp' claim. Access tokens issued to an application will have
/// the roles claim. Access tokens that contain both claims are issued only to users, where the scp
/// claim designates the delegated permissions, while the roles claim designates the user's role.
/// </summary>
[RequiredScopeOrAppPermission(
AcceptedScope = new string[] { _todoListRead, _todoListReadWrite },
AcceptedAppPermission = new string[] { _todoListReadAll, _todoListReadWriteAll }
)]
public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
{
// route logic ...
}
Web API endpoints should be prepared to accept calls from both users and applications, and should have control structures in place to respond to each accordingly. For instance, a call from a user via delegated permissions should be responded with user's data, while a call from an application via application permissions might be responded with the entire todolist. This is illustrated in the TodoListController controller:
// GET: api/TodoItems
[HttpGet]
[RequiredScopeOrAppPermission(
AcceptedScope = new string[] { _todoListRead, _todoListReadWrite },
AcceptedAppPermission = new string[] { _todoListReadAll, _todoListReadWriteAll }
)]
public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
{
if (!IsAppOnlyToken())
{
/// <summary>
/// The 'oid' (object id) is the only claim that should be used to uniquely identify
/// a user in an Azure AD tenant. The token might have one or more of the following claim,
/// that might seem like a unique identifier, but is not and should not be used as such:
///
/// - upn (user principal name): might be unique amongst the active set of users in a tenant
/// but tend to get reassigned to new employees as employees leave the organization and others
/// take their place or might change to reflect a personal change like marriage.
///
/// - email: might be unique amongst the active set of users in a tenant but tend to get reassigned
/// to new employees as employees leave the organization and others take their place.
/// </summary>
return await _context.TodoItems.Where(x => x.Owner == HttpContext.User.GetObjectId()).ToListAsync();
}
else
{
return await _context.TodoItems.ToListAsync();
}
}
/// <summary>
/// Indicates if the AT presented has application or delegated permissions.
/// </summary>
/// <returns></returns>
private bool IsAppOnlyToken()
{
// Add in the optional 'idtyp' claim to check if the access token is coming from an application or user.
// See: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims
if (HttpContext.User.Claims.Any(c => c.Type == "idtyp"))
{
return HttpContext.User.Claims.Any(c => c.Type == "idtyp" && c.Value == "app");
}
else
{
// alternatively, if an AT contains the roles claim but no scp claim, that indicates it's an app token
return HttpContext.User.Claims.Any(c => c.Type == "roles") && !HttpContext.User.Claims.Any(c => c.Type == "scp");
}
}
When granting access to data based on scopes, be sure to follow the principle of least privilege.
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.
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 [email protected] with any additional questions or comments.
- Microsoft identity platform (Azure Active Directory for developers)
- Overview of Microsoft Authentication Library (MSAL)
- Quickstart: Register an application with the Microsoft identity platform
- Quickstart: Configure a client application to access web APIs
- Initialize client applications using MSAL.js
- Handle MSAL.js exceptions and errors
- Logging in MSAL.js applications
- Microsoft Identity Web authentication library
- Logging in MSAL.NET applications
- Handle errors and exceptions in MSAL.NET
- Building Zero Trust ready apps
- National Clouds
- Azure AD code samples