page_type | name | description | languages | products | urlFragment | extensions | |||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
A Node headless application using MSAL Node to authenticate users with the device code flow against Customer Identity Access Management (CIAM) |
A Node headless application using MSAL Node to authenticate users with the device code flow against Customer Identity Access Management (CIAM) |
|
|
ms-identity-ciam-javascript-tutorial-4-sign-in-device-code |
|
A Node headless application using MSAL Node to authenticate users with the device code flow against Customer Identity Access Management (CIAM)
- Overview
- Scenario
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Contributing
- Learn More
This sample demonstrates a Node headless application that authenticates users with the device code flow against Azure AD for Customers.
- The client Node headless application uses MSAL Node to sign-in a user and obtain a JWT ID Token from Azure AD for Customers.
- The ID Token proves that the user has successfully authenticated against Azure AD for Customers.
File/folder | Description |
---|---|
index.js |
Main authentication logic resides here. |
authConfig.js |
Contains authentication parameters. |
- An Azure AD for Customers tenant. For more information, see: How to get an Azure AD for Customers tenant
- A user account in your Azure AD for Customers 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-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 1-Authentication\4-sign-in-device-code\App
npm install
There is one project in this sample. To register it, 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 directory, make sure you're using the directory that contains your Azure AD for Customers tenant:
- Select the Directories + subscriptions icon in the portal toolbar.
- On the Portal settings | Directories + subscriptions page, find your Azure AD for Customers tenant in the Directory name list, and then select Switch
Please refer to: Tutorial: Create user flow in Azure Active Directory CIAM
ℹ️ To enable password reset in Customer Identity Access Management (CIAM) in Azure Active Directory (Azure AD), please refer to: Tutorial: Enable self-service password reset
Please refer to:
- Navigate to the Azure portal and select the Azure AD for Customers 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-node-headless
. - 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.
- In the Advanced settings | Allow public client flows section, flip the switch for
Treat application as a public client
to Yes.- Click Save to save your changes.
- Since this app signs-in users, we will now proceed to select delegated permissions, which 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 openid, offline_access 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 it's a CIAM tenant, 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\authConfig.js
file. - 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_Application_Id_Here
and replace the existing value with the application ID (clientId) ofmsal-node-headless
app copied from the Azure portal.
cd 1-Authentication\4-sign-in-device-code\App
npm start
- Navigate to the project directory and run the
npm start
command. - Copy the suggested URL
https://microsoft.com/devicelogin
from the message in the terminal and open it in the browser. Then copy the device code from the message in the terminal. - Past the code in the Enter code prompt to sign in.
- Head back to the terminal to see your authentication information.
ℹ️ 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.
Expand for troubleshooting info
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
MSAL Node exposes acquireTokenByDeviceCode API to support the device authorization grant, which allows users to sign in to input-constrained devices such as a smart TV, IoT device, or a printer. To enable this flow, the device has the user visit a webpage in a browser on another device to sign in as shown in the code below:
const getTokenDeviceCode = (clientApplication) => {
/**
* Device Code Request for more information visit:
* https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_node.html#devicecoderequest
*/
const deviceCodeRequest = {
...loginRequest,
deviceCodeCallback: (response) => {
console.log(response.message);
},
};
/**
* The code below demonstrates the correct usage pattern of the acquireTokenByDeviceCode API.
* The application uses MSAL to obtain an Access Token through the Device Code grant.
* Once the device code request is executed, the user will be prompted by the headless application to visit a URL,
* where they will input the device code shown in the console. Once the code is entered, the promise below should resolve
* with an AuthenticationResult object. For information about acquireTokenByDeviceCode see:
* https://azuread.github.io/microsoft-authentication-library-for-js/ref/classes/_azure_msal_node.publicclientapplication.html#acquiretokenbydevicecode
*
*/
return clientApplication
.acquireTokenByDeviceCode(deviceCodeRequest)
.then((response) => {
return response;
})
.catch((error) => {
return error;
});
}
Once the user signs in, the device is able to get the user's authentication information.
getTokenDeviceCode(msalInstance).then(response => {
console.log(response)
});
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.