page_type | name | description | languages | products | urlFragment | extensions | ||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
A Node.js daemon application secured by MSAL Node on Microsoft identity platform |
This sample demonstrates how to use MSAL Node to acquire an access token for a protected resource in a daemon application using the application's own identity with the client credentials flow |
|
|
ms-identity-ciam-javascript-tutorial-3-call-api-node-daemon |
|
- Overview
- Scenario
- Contents
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- How to deploy this sample to Azure
- Contributing
- Learn More
This sample demonstrates how to use MSAL Node to acquire an access token for a protected resource in a daemon application using the application's own identity with the (client credentials flow).
Here you'll learn about access tokens, token validation, application permissions, and more.
- The Node.js daemon app obtains a JWT Access Token from Microsoft Entra External ID.
- The access token is used as a bearer token to authorize the user to call the ASP.NET Core web API protected by Microsoft Entra External ID.
- The service uses the Microsoft.Identity.Web to protect the Web api, check permissions and validate tokens.
File/folder | Description |
---|---|
App/.env |
Authentication parameters for the daemon app reside here. |
App/auth.js |
MSAL Node is initialized here. |
App/fetch.js |
logic to call the API reside here. |
API/ToDoListAPI/appsettings.json |
Authentication parameters for the API reside here. |
API/ToDoListAPI/Startup.cs |
Microsoft.Identity.Web is initialized here. |
- Either Visual Studio or Visual Studio Code and .NET Core SDK
- An external tenant. To create one, choose from the following methods:
- (Recommended) Use the Microsoft Entra External ID extension to set up an external tenant directly in Visual Studio Code.
- Create a new external tenant in the Microsoft Entra admin center.
- A user account with permissions to an external tenant.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-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 2-Authorization\3-call-api-node-daemon\App
npm install
There are two projects in this sample. Each needs to be separately registered in your external tenant. To register these projects, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Microsoft Entra 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.
-
Ensure that you have PowerShell 7 or later.
-
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.
ℹ️ This sample can make use of client certificates. You can use AppCreationScripts to register an Azure AD application with certificates. See: How to use certificates instead of client secrets
To manually register the apps, as a first step you'll need to:
- Sign in to the Microsoft Entra admin center.
- If your account is present in more than one Microsoft Entra External ID 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 Microsoft Entra External ID tenant.
- Navigate to the Microsoft Entra admin center and select the Microsoft Entra External ID 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
ciam-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 and Directory (tenant) 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 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
. - 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..
- 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
accessTokenAcceptedVersion
property 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 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_Application_Id_Here
and replace the existing value with the application ID (clientId) ofciam-msal-dotnet-api
app copied from the Microsoft Entra admin center. - Find the key
Enter_the_Tenant_Id_Here
and replace the existing value with your external tenant/directory ID. - Find the placeholder
Enter_the_Tenant_Subdomain_Here
and replace it with the Directory (tenant) subdomain. For instance, if your tenant primary domain iscontoso.onmicrosoft.com
, usecontoso
. If you don't have your tenant domain name, learn how to read your tenant details.
- Navigate to the Microsoft Entra admin center and select the Microsoft Entra External ID 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
ciam-msal-node-daemon
. - 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 Certificates & secrets blade in the left to open the page where you can generate secrets and upload certificates.
- In the Client secrets section, select New client secret:
- Type a key description (for instance
app secret
). - Select one of the available key durations (6 months, 12 months or Custom) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy and save the generated value for use in later steps.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Microsoft Entra admin center before navigating to any other screen or blade.
⚠️ For enhanced security, consider using certificates instead of client secrets. See: How to use certificates instead of secrets. - Type a key description (for instance
- Since this app signs-in as itself using the OAuth 2.0 client credentials flow, we will now proceed to select application permissions, which is required by apps authenticating as themselves.
- 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
ciam-msal-dotnet-api
.- We will select “Application permissions”, which should be the type of permissions that apps should use when they are authenticating just as themselves and not signing-in users.
- In the Application permissions section, select the ToDoList.Read.All, ToDoList.ReadWrite.All in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- At this stage, the permissions are assigned correctly but since the client app does not allow users to interact, the users' themselves cannot consent to these permissions. To get around this problem, we'd let the tenant administrator consent on behalf of all users in the tenant. Select the Grant admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all accounts in the tenant. You need to be a tenant admin to be able to carry out this operation.
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
APP\.env
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofciam-msal-node-daemon
app copied from the Microsoft Entra admin center. - Find the placeholder
Enter_the_Tenant_Subdomain_Here
and replace it with the Directory (tenant) subdomain. For instance, if your tenant primary domain iscontoso.onmicrosoft.com
, usecontoso
. If you don't have your tenant domain name, learn how to read your tenant details. - Find the key
Enter_the_Client_Secret_Here
and replace the existing value with the generated secret that you saved during the creation ofciam-msal-node-daemon
copied from the Microsoft Entra admin center. - Find the key
Enter_the_Web_Api_Application_Id_Here
and replace the existing value with the application ID (clientId) ofciam-msal-dotnet-api
app copied from the Microsoft Entra admin center.
From your shell or command line, execute the following commands:
cd 2-Authorization\3-call-api-node-daemon\API\ToDoListAPI
dotnet run
Then, open a separate command terminal and run:
2-Authorization\3-call-api-node-daemon\App
node . --op getToDos
- Navigate to the app root directory in the terminal.
- Enter the following command
node . --op getToDos
.
ℹ️ 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
node
ms-identity
adal
msal
].
If you find a bug in the sample, raise the issue on GitHub Issues.
You need to instantiate MSAL Node as a ConfidentialClientApplication to support the (client credentials flow).
const msal = require('@azure/msal-node');
const cca = new msal.ConfidentialClientApplication(msalConfig);
Access Token requests in MSAL.js are meant to be per-resource-per-scope(s). This means that an Access Token requested for resource A with scope scp1
:
- cannot be used for accessing resource A with scope
scp2
, and, - cannot be used for accessing resource B of any scope.
The intended recipient of an Access Token is represented by the aud
claim; in case the value for the aud
claim does not mach the resource APP ID URI, the token should be considered invalid. Likewise, the permissions that an Access Token grants is represented by the roles
claim. See Access Token claims for more information.
To get the access token for a protected resource using the client credentials grant flow, MSAL Node exposes acquireTokenByClientCredential
API to grant permission to the application to get an access token.
const cca = new msal.ConfidentialClientApplication(msalConfig);
async function getToken(tokenRequest) {
return await cca.acquireTokenByClientCredential(tokenRequest);
}
On the web API side, the AddMicrosoftIdentityWebApi
method in Program.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.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
builder.Configuration.Bind("AzureAd", options);
options.Events = new JwtBearerEvents();
}, options => { builder.Configuration.Bind("AzureAd", options); });
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]
[RequiredScopeOrAppPermission(
RequiredScopesConfigurationKey = "AzureAD:Scopes:Read",
RequiredAppPermissionsConfigurationKey = "AzureAD:AppPermissions:Read"
)]
public async Task<IActionResult> GetAsync()
{
var toDos = await _toDoContext.ToDos!
.Where(td => RequestCanAccessToDo(td.Owner))
.ToListAsync();
return Ok(toDos);
}
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:
private bool RequestCanAccessToDo(Guid userId)
{
return IsAppMakingRequest() || (userId == GetUserId());
}
[HttpGet]
[RequiredScopeOrAppPermission(
RequiredScopesConfigurationKey = "AzureAD:Scopes:Read",
RequiredAppPermissionsConfigurationKey = "AzureAD:AppPermissions:Read"
)]
public async Task<IActionResult> GetAsync()
{
var toDos = await _toDoContext.ToDos!
.Where(td => RequestCanAccessToDo(td.Owner))
.ToListAsync();
return Ok(toDos);
}
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.
Expand the section
There is one web API in this sample. To deploy it to Azure App Services, you'll need to:
- create an Azure App Service
- publish the projects to the App Services
⚠️ Please make sure that you have not switched on the Automatic authentication provided by App Service. It interferes the authentication code used in this code example.
Follow the link to Publish with Visual Studio.
- Install the Visual Studio Code extension Azure App Service.
- Follow the link to Publish with Visual Studio Code
ℹ️ When calling the web API, your app may receive an error similar to the following:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some-url-here. (Reason: additional information here).
If that's the case, you'll need enable cross-origin resource sharing (CORS) for you web API. Follow the steps below to do this:
- Go to Microsoft Entra admin center, and locate the web API project that you've deployed to App Service.
- On the API blade, select CORS. Check the box Enable Access-Control-Allow-Credentials.
- Under Allowed origins, add the URL of your published web app that will call this web API.
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.
- Configure your company branding
- OAuth 2.0 authorization with Microsoft Entra ID
- Language customization in Microsoft Entra External ID
- Building Zero Trust ready apps
- 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