page_type | languages | products | urlFragment | description | |||||
---|---|---|---|---|---|---|---|---|---|
sample |
|
|
active-directory-b2c-javascript-nodejs-webapi |
This sample demonstrates a JavaScript SPA application calling a Node.js Web Api that is secured using Azure AD B2C |
A sample demonstrating how to protect a Node.js Web API with Azure AD B2C using the Passport.js library
- 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 protect a Node.js Web API with Microsoft identity platform and Azure AD B2C using the passport-azure-ad library.
You will need a client application for calling the Web API. Choose:
- The client application uses the Microsoft Authentication Library for JavaScript (MSAL.js) to sign-in a user and obtain a JWT Access Token from Azure AD B2C.
- The Access Token is used as a bearer token to authenticate the user when calling this web API.
- The web API responds with the name of the user obtained from the token claims.
File/folder | Description |
---|---|
config.js |
Contains configuration parameters for the sample. |
index.js |
Main application logic resides here. |
process.json |
Contains configuration parameters for logging via Morgan. |
- Node.js must be installed to run this sample.
- A modern web browser. This sample uses ES6 conventions and will not run on Internet Explorer.
- Visual Studio Code is recommended for running and editing this sample.
- VS Code Azure Tools extension is recommended for interacting with Azure through VS Code Interface.
- An Azure AD B2C tenant. For more information see: How to get an Azure AD B2C tenant
- A user account in your Azure AD B2C. This sample will not work with a personal Microsoft account. Therefore, if you signed in to the Azure portal with a personal account and have never created a user account in your directory before, you need to do that now.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi.git
or download and extract the repository .zip file.
⚠️ Given that the name of the sample is quite long, and so are the names of the referenced packages, you might want to clone it in a folder close to the root of your hard drive, to avoid maximum file path length limitations on Windows.
cd active-directory-b2c-javascript-nodejs-webapi
npm install
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 B2C 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 B2C tenant.
Please refer to: Tutorial: Create user flows in Azure Active Directory B2C
Please refer to: Tutorial: Add identity providers to your applications in Azure Active Directory B2C
- Navigate to the Azure portal and select the Azure AD B2C 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
active-directory-b2c-javascript-nodejs-webapi
. - Under Supported account types, select Accounts in any organizational directory only.
- 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 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
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.
- 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
demo.read
. - For Admin consent display name type
Access active-directory-b2c-javascript-nodejs-webapi
- For Admin consent description type
Allows the app to access active-directory-b2c-javascript-nodejs-webapi as the signed-in user.
- Keep State as Enabled
- Click on 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:
- On the right side menu, select the
Manifest
blade.- Set
accessTokenAcceptedVersion
property to 2. - Click on Save.
- Set
Configure the service app (active-directory-b2c-javascript-nodejs-webapi) to use your app registration
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
config.json
file. - Find the key
tenantName
and replace the existing value with your Azure AD B2C tenant's name e.g.fabrikamb2c
. - Find the key
clientID
and replace the existing value with the application ID (clientId) of theactive-directory-b2c-javascript-nodejs-webapi
application copied from the Azure Portal. - Find the key
policyName
and replace the existing value with name of the policy you've created, e.g.B2C_1_SUSI
.
cd active-directory-b2c-javascript-nodejs-webapi
npm start
Call this web API from your client application. Upon an authorized call, the web API will respond by:
res.status(200).json({'name': req.authInfo['name']});
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Consider taking a moment to share your experience with us.
passport-azure-ad validates the token against the issuer
, scope
and audience
claims (defined in BearerStrategy
constructor) using the passport.authenticate()
API:
app.get('/hello', passport.authenticate('oauth-bearer', { session: false }),
(req, res) => {
console.log('Validated claims: ', req.authInfo);
);
- What is Azure Active Directory B2C?
- Application types that can be used in Active Directory B2C
- Recommendations and best practices for Azure Active Directory B2C
- Azure AD B2C session
- Initialize client applications using MSAL.js
- Single sign-on with MSAL.js
- Handle MSAL.js exceptions and errors
- Logging in MSAL.js applications
- Pass custom state in authentication requests using MSAL.js
- Prompt behavior in MSAL.js interactive requests
- Use MSAL.js to work with Azure AD B2C
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
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, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following 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 [email protected] with any additional questions or comments.