Git Product home page Git Product logo

active-directory-javascript-nodejs-webapi-v2's Introduction

page_type languages products urlFragment description
sample
javascript
nodejs
azure-active-directory
microsoft-identity-platform
active-directory-javascript-nodejs-webapi-v2
This sample demonstrates how to protect a Node.js Web API that is secured using Azure AD

Protect a Node.js web API with Microsoft identity platform

  1. Overview
  2. Scenario
  3. Contents
  4. Prerequisites
  5. Setup
  6. Registration
  7. Running the sample
  8. Explore the sample
  9. About the code
  10. Deployment
  11. More information
  12. Community Help and Support
  13. Contributing
  14. Code of Conduct

Overview

This sample demonstrates how to protect a Node.js Web API with the Microsoft identity platform and Azure Active Directory (Azure AD) using the passport-azure-ad library.

You will need a client application for calling the web API. For a web API sample that is coupled with a client app, see: JavaScript Single-page application & Node.js web API Tutorial

Alternatively, you may modify the following samples to call this web API (this requires some familiarity, so follow the tutorial above first):

For best results, configure your client app in parallel with configuring this API sample.

Scenario

  1. 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.
  2. The Access Token is used as a bearer token to authenticate the user when calling this Web API.

Overview

Contents

File/folder Description
AppCreationScripts Contains automation scripts for app registration.
process.json Contains configuration parameters for logging via Bunyan.
index.js Main application logic resides here.
config.json Contains configuration parameters for the sample.
.gitignore Defines what to ignore at commit time.
CHANGELOG.md List of changes to the sample.
CONTRIBUTING.md Guidelines for contributing to the sample.
LICENSE The license for the sample.
package.json Package manifest for npm.
README.md This README file.
SECURITY.md Security disclosures.

Prerequisites

  • 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 tenant. For more information see: How to get an Azure AD tenant
  • A user account in your Azure AD. 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.

Setup

Step 1: Clone or download this repository

From your shell or command line:

    git clone https://github.com/Azure-Samples/active-directory-javascript-nodejs-webapi-v2.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.

Step 2: Install project dependencies

    cd active-directory-javascript-nodejs-webapi-v2
    npm install

Register the sample application(s) with your Azure Active Directory tenant

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 Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.

  1. On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory

  2. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  3. Run the script to create your Azure AD application and configure the code of the sample application accordingly.

  4. 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.

Choose the Azure AD tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Azure portal.
  2. 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.

Register the service app (active-directory-javascript-nodejs-webapi-v2)

  1. Navigate to the Azure portal and select the Azure AD service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. 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-javascript-nodejs-webapi-v2.
    • Under Supported account types, select Accounts in this organizational directory only.
  4. Select Register to create the application.
  5. 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.
  6. Select Save to save your changes.
  7. 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.
  8. 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 active-directory-javascript-nodejs-webapi-v2
      • For Admin consent description type Allows the app to access active-directory-javascript-nodejs-webapi-v2 as the signed-in user.
      • For User consent display name type Access active-directory-javascript-nodejs-webapi-v2
      • For User consent description type Allow the application to access active-directory-javascript-nodejs-webapi-v2 on your behalf.
      • Keep State as Enabled
      • Click on the Add scope button on the bottom to save this scope.
  9. On the right side menu, select the Manifest blade.
    • Set accessTokenAcceptedVersion property to 2.
    • Click on Save.

Configure the service app (active-directory-javascript-nodejs-webapi-v2) 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".

  1. Open the config.js file.
  2. Find the key clientID and replace the existing value with the application ID (clientId) of the active-directory-javascript-nodejs-webapi-v2 application copied from the Azure portal.
  3. Find the key tenantID and replace the existing value with your Azure AD tenant ID.
  4. Find the key audience and replace the existing value with the application ID (clientId) of the active-directory-javascript-nodejs-webapi-v2 application copied from the Azure portal.

Running the sample

Run the Web API! By default it will run on http://localhost:5000/api

    cd active-directory-javascript-nodejs-webapi-v2
    npm start

When you start the Web API, depending on the browser you use, you'll get:

  • an empty web page (case with Microsoft Edge)
  • or an error HTTP 401 (case with Chrome)

Explore the sample

To call this web API from a client application:

  1. Make sure that the client app is registered on the same tenant as this API.

  2. Locate the client app's registration screen, click on 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 active-directory-javascript-nodejs-webapi-v2.
    • In the Delegated permissions section, select the access_as_user in the list. Use the search box if necessary.
    • Click on the Add permissions button at the bottom.
  3. Update the config of the client app to point it to this Web API:

    1. For example, in this, open the App\apiConfig.js file . Then:
      1. Find the key Enter_the_Web_Api_Uri_Here and replace the existing value with the coordinates of this web API, i.e. http://localhost:5000/api.
      2. Find the key Enter_the_Web_Api_Scope_Here and replace the existing value with the scopes for this web API, like api://e767d418-b80b-4568-9754-557f40697fc5/access_as_user. You can copy this from the Expose an API blade of this Web APIs registration.
  4. Use the steps provided in the client app sample's documentation to run the app, sign-in a user and make a call to 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']
      });

Overview

ℹ️ How did we do? Consider sharing your experience with us

About the code

Token Validation

passport-azure-ad validates the token against the issuer, scope and audience claims (defined in BearerStrategy constructor) using the passport.authenticate() API:

    app.get('/api', passport.authenticate('oauth-bearer', { session: false }),
        (req, res) => {
            console.log('Validated claims: ', req.authInfo);
    );

Deployment

Deployment to Azure App Services

There is one web project 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, and
  • update its client(s) to call the web site instead of the local environment.

Create and publish active-directory-javascript-nodejs-webapi-v2 to an Azure App Services

ℹ️ If you would like to use VS Code Azure Tools extension for deployment, watch the tutorial offered by Microsoft Docs.

  1. Sign in to the Azure portal.
  2. Click Create a resource in the top left-hand corner, select Web --> Web App, and give your web site a name, for example, active-directory-javascript-nodejs-webapi-v2.azurewebsites.net.
  3. Next, select the Subscription, Resource Group, App service plan and Location. OS will be Windows and Publish will be Code.
  4. Click Create and wait for the App Service to be created.
  5. Once you get the Deployment succeeded notification, then click on Go to resource to navigate to the newly created App service.
  6. Once the web site is created, locate it in the Dashboard and click it to open App Services Overview screen.

⚠️ After deployment, navigate to the CORS blade on the portal and enable it. Once you do, add your client application's domain.

Update the Azure AD app registration for active-directory-javascript-nodejs-webapi-v2
  1. Navigate back to to the Azure portal. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations (Preview).
  2. In the resulting screen, select the active-directory-javascript-nodejs-webapi-v2 application.
  3. From the Branding menu, update the Home page URL, to the address of your service, for example https://active-directory-javascript-nodejs-webapi-v2.azurewebsites.net. Save the configuration.
  4. Add the same URL in the list of values of the Authentication -> Redirect URIs menu. If you have multiple redirect URIs, make sure that there a new entry using the App service's URI for each redirect URI.

More information

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.

Community Help and Support

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.

Contributing

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.

active-directory-javascript-nodejs-webapi-v2's People

Contributors

danieldobalian avatar derisen avatar jmprieur avatar joeho888 avatar kalyankrishna1 avatar kjyam98 avatar microsoftopensource avatar msftgits avatar navyasric avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.