├── .github ├── CODE_OF_CONDUCT.md ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── CodeFactor Badge ├── LICENSE ├── README.md ├── ReadmeFiles ├── screenshot.png └── topology.png ├── SECURITY.md ├── config.json ├── index.js ├── package.json ├── process.json └── todolist.js /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | > Please provide us with the following information: 5 | > --------------------------------------------------------------- 6 | 7 | ### This issue is for a: (mark with an `x`) 8 | ``` 9 | - [ ] bug report -> please search issues before submitting 10 | - [ ] question 11 | - [ ] feature request 12 | - [ ] documentation issue or request 13 | - [ ] regression (a behavior that used to work and stopped in a new release) 14 | ``` 15 | 16 | ### Minimal steps to reproduce 17 | > 18 | 19 | ### Any log messages given by the failure 20 | > 21 | 22 | ### Expected/desired behavior 23 | > 24 | 25 | ### Browser and version? 26 | > 27 | 28 | ### Versions 29 | > 30 | 31 | ### Mention any other details that might be useful 32 | 33 | > --------------------------------------------------------------- 34 | > Thanks! We'll be in touch soon. 35 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | * ... 4 | 5 | ## Does this introduce a breaking change? 6 | 7 | ``` 8 | [ ] Yes 9 | [ ] No 10 | ``` 11 | 12 | ## Pull Request Type 13 | What kind of change does this Pull Request introduce? 14 | 15 | 16 | ``` 17 | [ ] Bugfix 18 | [ ] Feature 19 | [ ] Code style update (formatting, local variables) 20 | [ ] Refactoring (no functional changes, no api changes) 21 | [ ] Documentation content changes 22 | [ ] Other... Please describe: 23 | ``` 24 | 25 | ## How to Test 26 | * Get the code 27 | 28 | ``` 29 | git clone [repo-address] 30 | cd [repo-name] 31 | git checkout [branch-name] 32 | npm install 33 | ``` 34 | 35 | * Test the code 36 | 37 | ``` 38 | ``` 39 | 40 | ## What to Check 41 | Verify that the following are valid 42 | * ... 43 | 44 | ## Other Information 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | package-lock.json 2 | node_modules -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | 3 | ## 10/01/2020 4 | 5 | * Token validation logic revised. 6 | 7 | ## 08/05/2020 8 | 9 | * Added issue & PR templates. 10 | 11 | ## 03/21/2020 12 | 13 | * Switch to using the tenant domain name for the tenant ID in [config.js](config.js). 14 | * Update README to reflect current state of sample and the articles referenced on [docs.microsoft.com](https://docs.microsoft.com/azure/active-directory-b2c). 15 | 16 | ## 03/04/2020 17 | 18 | * Dependencies updated. 19 | * Configuration parameters separated. 20 | * README improved. 21 | * ES6 conventions introduced. 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 5 | the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. 6 | 7 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide 8 | a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions 9 | provided by the bot. You will only need to do this once across all repos using our CLA. 10 | 11 | ## Instructions 12 | 13 | Follow these instructions to download and run the sample locally. 14 | 15 | 1. Install [Node](https://nodejs.org/). 16 | 2. Clone and download this repository. 17 | 3. Navigate to the root of this repository, and install the dependencies: `npm install` 18 | 4. Start the application: `npm start` 19 | -------------------------------------------------------------------------------- /CodeFactor Badge: -------------------------------------------------------------------------------- 1 | [![CodeFactor](https://www.codefactor.io/repository/github/chaos-ui/active-directory-b2c-javascript-nodejs-webapi/badge)](https://www.codefactor.io/repository/github/chaos-ui/active-directory-b2c-javascript-nodejs-webapi) 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | languages: 4 | - javascript 5 | products: 6 | - nodejs 7 | - ms-graph 8 | - azure-active-directory 9 | - azure-active-directory-b2c 10 | urlFragment: active-directory-b2c-javascript-nodejs-webapi 11 | description: "This sample demonstrates a JavaScript SPA application calling a Node.js Web Api that is secured using Azure AD B2C" 12 | --- 13 | # A sample demonstrating how to protect a Node.js Web API with Azure AD B2C using the Passport.js library 14 | 15 | 1. [Overview](#overview) 16 | 1. [Scenario](#scenario) 17 | 1. [Contents](#contents) 18 | 1. [Prerequisites](#prerequisites) 19 | 1. [Setup](#setup) 20 | 1. [Registration](#registration) 21 | 1. [Running the sample](#running-the-sample) 22 | 1. [Explore the sample](#explore-the-sample) 23 | 1. [About the code](#about-the-code) 24 | 1. [More information](#more-information) 25 | 1. [Community Help and Support](#community-help-and-support) 26 | 1. [Contributing](#contributing) 27 | 28 | ## Overview 29 | 30 | This sample demonstrates [how to protect a Node.js Web API](https://docs.microsoft.com/azure/active-directory/develop/quickstart-configure-app-expose-web-apis) with [Microsoft identity platform](https://docs.microsoft.com/azure/active-directory/develop/) and [Azure AD B2C](https://docs.microsoft.com/azure/active-directory-b2c/overview) using the [passport-azure-ad](https://github.com/AzureAD/passport-azure-ad) library. 31 | 32 | You will need a **client** application for calling the Web API. Choose: 33 | 34 | - [JavaScript Single-page Application calling a custom Web API with MSAL.js 2.x using the auth code flow with PKCE](https://github.com/Azure-Samples/ms-identity-b2c-javascript-spa). 35 | 36 | ## Scenario 37 | 38 | 1. The client application uses the [Microsoft Authentication Library for JavaScript (MSAL.js)](https://github.com/AzureAD/microsoft-authentication-library-for-js) to sign-in a user and obtain a JWT [Access Token](https://docs.microsoft.com/azure/active-directory/develop/access-tokens) from **Azure AD B2C**. 39 | 1. The **Access Token** is used as a *bearer* token to authenticate the user when calling this web API. 40 | 1. The web API responds with the name of the user obtained from the token claims. 41 | 42 | ![Overview](./ReadmeFiles/topology.png) 43 | 44 | ## Contents 45 | 46 | | File/folder | Description | 47 | |----------------------|-----------------------------------------------------------| 48 | | `config.js` | Contains configuration parameters for the sample. | 49 | | `index.js` | Main application logic resides here. | 50 | | `process.json` | Contains configuration parameters for logging via Morgan. | 51 | 52 | ## Prerequisites 53 | 54 | - [Node.js](https://nodejs.org/en/download/) must be installed to run this sample. 55 | - A modern web browser. This sample uses **ES6** conventions and will not run on **Internet Explorer**. 56 | - [Visual Studio Code](https://code.visualstudio.com/download) is recommended for running and editing this sample. 57 | - [VS Code Azure Tools](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack) extension is recommended for interacting with Azure through VS Code Interface. 58 | - An **Azure AD B2C** tenant. For more information see: [How to get an Azure AD B2C tenant](https://docs.microsoft.com/azure/active-directory-b2c/tutorial-create-tenant) 59 | - 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](https://portal.azure.com) with a personal account and have never created a user account in your directory before, you need to do that now. 60 | 61 | ## Setup 62 | 63 | ### Step 1: Clone or download this repository 64 | 65 | From your shell or command line: 66 | 67 | ```console 68 | git clone https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi.git 69 | ``` 70 | 71 | or download and extract the repository .zip file. 72 | 73 | > :warning: 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. 74 | 75 | ### Step 2: Install project dependencies 76 | 77 | ```console 78 | cd active-directory-b2c-javascript-nodejs-webapi 79 | npm install 80 | ``` 81 | 82 | ### Register the sample application(s) with your Azure Active Directory tenant 83 | 84 | :warning: This sample comes with a pre-registered application for testing purposes. If you would like to use your own **Azure AD B2C** tenant and application, follow the steps below to register and configure the application in the **Azure Portal**. Otherwise, continue with the steps for [Running the sample](#running-the-sample). 85 | 86 | ### Choose the Azure AD tenant where you want to create your applications 87 | 88 | As a first step you'll need to: 89 | 90 | 1. Sign in to the [Azure portal](https://portal.azure.com). 91 | 1. 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. 92 | 93 | ### Create User Flows and Custom Policies 94 | 95 | Please refer to: [Tutorial: Create user flows in Azure Active Directory B2C](https://docs.microsoft.com/azure/active-directory-b2c/tutorial-create-user-flows) 96 | 97 | ### Add External Identity Providers 98 | 99 | Please refer to: [Tutorial: Add identity providers to your applications in Azure Active Directory B2C](https://docs.microsoft.com/azure/active-directory-b2c/tutorial-add-identity-providers) 100 | 101 | ### Register the service app (active-directory-b2c-javascript-nodejs-webapi) 102 | 103 | 1. Navigate to the [Azure portal](https://portal.azure.com) and select the **Azure AD B2C** service. 104 | 1. Select the **App Registrations** blade on the left, then select **New registration**. 105 | 1. In the **Register an application page** that appears, enter your application's registration information: 106 | - 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`. 107 | - Under **Supported account types**, select **Accounts in any organizational directory only**. 108 | 1. Select **Register** to create the application. 109 | 1. 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. 110 | 1. Select **Save** to save your changes. 111 | 1. 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](https://docs.microsoft.com/azure/active-directory/develop/access-tokens) for. 112 | The first thing that we need to do is to declare the unique [resource](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow) URI that the clients will be using to obtain access tokens for this API. To declare an resource URI, follow the following steps: 113 | - Click `Set` next to the **Application ID URI** to generate a URI that is unique for this app. 114 | - For this sample, accept the proposed Application ID URI (api://{clientId}) by selecting **Save**. 115 | 1. All APIs have to publish a minimum of one [scope](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code) for the client's to obtain an access token successfully. To publish a scope, follow the following steps: 116 | - Select **Add a scope** button open the **Add a scope** screen and Enter the values as indicated below: 117 | - For **Scope name**, use `demo.read`. 118 | - For **Admin consent display name** type `Access active-directory-b2c-javascript-nodejs-webapi` 119 | - For **Admin consent description** type `Allows the app to access active-directory-b2c-javascript-nodejs-webapi as the signed-in user.` 120 | - Keep **State** as **Enabled** 121 | - Click on the **Add scope** button on the bottom to save this scope. 122 | 1. On the right side menu, select the `Manifest` blade. 123 | - Set `accessTokenAcceptedVersion` property to **2**. 124 | - Click on **Save**. 125 | 126 | #### Configure the service app (active-directory-b2c-javascript-nodejs-webapi) to use your app registration 127 | 128 | Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code. 129 | 130 | > In the steps below, "ClientID" is the same as "Application ID" or "AppId". 131 | 132 | 1. Open the `config.json` file. 133 | 1. Find the key `tenantName` and replace the existing value with your **Azure AD B2C** tenant's name e.g. `fabrikamb2c`. 134 | 1. Find the key `clientID` and replace the existing value with the application ID (clientId) of the `active-directory-b2c-javascript-nodejs-webapi` application copied from the **Azure Portal**. 135 | 1. Find the key `policyName` and replace the existing value with name of the policy you've created, e.g. `B2C_1_SUSI`. 136 | 137 | ## Running the sample 138 | 139 | ```console 140 | cd active-directory-b2c-javascript-nodejs-webapi 141 | npm start 142 | ``` 143 | 144 | ## Explore the sample 145 | 146 | Call this web API from your client application. Upon an authorized call, the web API will respond by: 147 | 148 | ```javascript 149 | res.status(200).json({'name': req.authInfo['name']}); 150 | ``` 151 | 152 | > :information_source: Did the sample not work for you as expected? Then please reach out to us using the [GitHub Issues](../../../../issues) page. 153 | 154 | ## We'd love to hear from you 155 | 156 | Consider taking a moment to [share your experience with us](https://forms.office.com/Pages/ResponsePage.aspx?id=v4j5cvGGr0GRqy180BHbR73pcsbpbxNJuZCMKN0lURpURFBLRlBRMk9ZMjFDOFA4UVBVOE9TVExJSSQlQCN0PWcu). 157 | 158 | ## About the code 159 | 160 | ### Token Validation 161 | 162 | [passport-azure-ad](https://github.com/AzureAD/passport-azure-ad) validates the token against the `issuer`, `scope` and `audience` claims (defined in `BearerStrategy` constructor) using the `passport.authenticate()` API: 163 | 164 | ```javascript 165 | app.get('/hello', passport.authenticate('oauth-bearer', { session: false }), 166 | (req, res) => { 167 | console.log('Validated claims: ', req.authInfo); 168 | ); 169 | ``` 170 | 171 | ## More information 172 | 173 | - [What is Azure Active Directory B2C?](https://docs.microsoft.com/azure/active-directory-b2c/overview) 174 | - [Application types that can be used in Active Directory B2C](https://docs.microsoft.com/azure/active-directory-b2c/application-types) 175 | - [Recommendations and best practices for Azure Active Directory B2C](https://docs.microsoft.com/azure/active-directory-b2c/best-practices) 176 | - [Azure AD B2C session](https://docs.microsoft.com/azure/active-directory-b2c/session-overview) 177 | - [Initialize client applications using MSAL.js](https://docs.microsoft.com/azure/active-directory/develop/msal-js-initializing-client-applications) 178 | - [Single sign-on with MSAL.js](https://docs.microsoft.com/azure/active-directory/develop/msal-js-sso) 179 | - [Handle MSAL.js exceptions and errors](https://docs.microsoft.com/azure/active-directory/develop/msal-handling-exceptions?tabs=javascript) 180 | - [Logging in MSAL.js applications](https://docs.microsoft.com/azure/active-directory/develop/msal-logging?tabs=javascript) 181 | - [Pass custom state in authentication requests using MSAL.js](https://docs.microsoft.com/azure/active-directory/develop/msal-js-pass-custom-state-authentication-request) 182 | - [Prompt behavior in MSAL.js interactive requests](https://docs.microsoft.com/azure/active-directory/develop/msal-js-prompt-behavior) 183 | - [Use MSAL.js to work with Azure AD B2C](https://docs.microsoft.com/azure/active-directory/develop/msal-b2c-overview) 184 | 185 | For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see [Authentication Scenarios for Azure AD](https://docs.microsoft.com/azure/active-directory/develop/authentication-flows-app-scenarios). 186 | 187 | ## Community Help and Support 188 | 189 | Use [Stack Overflow](http://stackoverflow.com/questions/tagged/msal) to get support from the community. 190 | Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. 191 | Make sure that your questions or comments are tagged with [`azure-active-directory` `azure-ad-b2c` `ms-identity` `adal` `msal`]. 192 | 193 | If you find a bug in the sample, please raise the issue on [GitHub Issues](../../issues). 194 | 195 | To provide a recommendation, visit the following [User Voice page](https://feedback.azure.com/forums/169401-azure-active-directory). 196 | 197 | ## Contributing 198 | 199 | If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md). 200 | 201 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 202 | -------------------------------------------------------------------------------- /ReadmeFiles/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi/49d6f813928a4c2ed41295c8dc043f8aac8f727b/ReadmeFiles/screenshot.png -------------------------------------------------------------------------------- /ReadmeFiles/topology.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi/49d6f813928a4c2ed41295c8dc043f8aac8f727b/ReadmeFiles/topology.png -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | ## Security 2 | 3 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 4 | 5 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)) of a security vulnerability, please report it to us as described below. 6 | 7 | ## Reporting Security Issues 8 | 9 | **Please do not report security vulnerabilities through public GitHub issues.** 10 | 11 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). 12 | 13 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). 14 | 15 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). 16 | 17 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 18 | 19 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 20 | * Full paths of source file(s) related to the manifestation of the issue 21 | * The location of the affected source code (tag/branch/commit or direct URL) 22 | * Any special configuration required to reproduce the issue 23 | * Step-by-step instructions to reproduce the issue 24 | * Proof-of-concept or exploit code (if possible) 25 | * Impact of the issue, including how an attacker might exploit the issue 26 | 27 | This information will help us triage your report more quickly. 28 | 29 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. 30 | 31 | ## Preferred Languages 32 | 33 | We prefer all communications to be in English. 34 | 35 | ## Policy 36 | 37 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "credentials": { 3 | "tenantName": "fabrikamb2c", 4 | "clientID": "Enter_the_Application_Id_Here" 5 | }, 6 | "policies": { 7 | "policyName": "B2C_1_susi" 8 | }, 9 | "resource": { 10 | "scope": ["tasks.read"] 11 | }, 12 | "metadata": { 13 | "authority": "login.microsoftonline.com", 14 | "discovery": ".well-known/openid-configuration", 15 | "version": "v2.0" 16 | }, 17 | "settings": { 18 | "isB2C": true, 19 | "validateIssuer": true, 20 | "passReqToCallback": false, 21 | "loggingLevel": "info" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const morgan = require('morgan'); 3 | const passport = require('passport'); 4 | const config = require('./config.json'); 5 | const todolist = require('./todolist'); 6 | const cors = require('cors'); 7 | 8 | // 9 | const BearerStrategy = require('passport-azure-ad').BearerStrategy; 10 | // 11 | 12 | global.global_todos = []; 13 | 14 | // 15 | const options = { 16 | identityMetadata: `https://${config.credentials.tenantName}.b2clogin.com/${config.credentials.tenantName}.onmicrosoft.com/${config.policies.policyName}/${config.metadata.version}/${config.metadata.discovery}`, 17 | clientID: config.credentials.clientID, 18 | audience: config.credentials.clientID, 19 | policyName: config.policies.policyName, 20 | isB2C: config.settings.isB2C, 21 | validateIssuer: config.settings.validateIssuer, 22 | loggingLevel: config.settings.loggingLevel, 23 | passReqToCallback: config.settings.passReqToCallback 24 | } 25 | 26 | // 27 | 28 | // 29 | const bearerStrategy = new BearerStrategy(options, (token, done) => { 30 | // Send user info using the second argument 31 | done(null, { }, token); 32 | } 33 | ); 34 | // 35 | const app = express(); 36 | 37 | app.use(express.json()); 38 | 39 | //enable CORS (for testing only -remove in production/deployment) 40 | app.use((req, res, next) => { 41 | res.header('Access-Control-Allow-Origin', '*'); 42 | res.header('Access-Control-Allow-Headers', 'Authorization, Origin, X-Requested-With, Content-Type, Accept'); 43 | next(); 44 | }); 45 | 46 | app.use(morgan('dev')); 47 | 48 | app.use(passport.initialize()); 49 | 50 | passport.use(bearerStrategy); 51 | 52 | // To do list endpoints 53 | app.use('/api/todolist', todolist); 54 | 55 | // 56 | // API endpoint, one must present a bearer accessToken to access this endpoint 57 | app.get('/hello', 58 | passport.authenticate('oauth-bearer', {session: false}), 59 | (req, res) => { 60 | console.log('Validated claims: ', req.authInfo); 61 | 62 | 63 | // Service relies on the name claim. 64 | res.status(200).json({'name': req.authInfo['name']}); 65 | } 66 | ); 67 | // 68 | 69 | // 70 | // API anonymous endpoint, returns a date to the caller. 71 | app.get('/public', (req, res) => res.send( {'date': new Date() } )); 72 | // 73 | 74 | const port = process.env.PORT || 5000; 75 | 76 | app.listen(port, () => { 77 | console.log('Listening on port ' + port); 78 | }); 79 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "active-directory-b2c-javascript-nodejs-webapi", 3 | "version": "1.0.0", 4 | "description": "---\r page_type: sample\r description: \"This sample demonstrates how to protect a Node.js web API with Azure AD B2C using the Passport.js library.\"\r languages:\r - javascript\r - nodejs\r products:\r - azure\r - azure-active-directory\r urlFragment: nodejs-web-api-azure-ad\r ---", 5 | "author": "derisen", 6 | "license": "ISC", 7 | "engines": { 8 | "node": ">=6.9.1" 9 | }, 10 | "scripts": { 11 | "start": "node index.js", 12 | "dev": "nodemon index.js" 13 | }, 14 | "dependencies": { 15 | "cors": "^2.8.5", 16 | "express": "^4.14.0", 17 | "morgan": "^1.7.0", 18 | "passport": "^0.4.1", 19 | "passport-azure-ad": "^4.2.1" 20 | }, 21 | "main": "index.js", 22 | "repository": { 23 | "type": "git", 24 | "url": "git+https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi.git" 25 | }, 26 | "bugs": { 27 | "url": "https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi/issues" 28 | }, 29 | "homepage": "https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi#readme", 30 | "devDependencies": { 31 | "nodemon": "^2.0.2" 32 | }, 33 | "keywords": [ 34 | "azure", 35 | "ad", 36 | "node.js", 37 | "b2c", 38 | "api" 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /process.json: -------------------------------------------------------------------------------- 1 | { 2 | "name" : "worker", 3 | "script" : "./index.js", 4 | "instances" : 1, 5 | "merge_logs" : true, 6 | "log_date_format" : "YYYY-MM-DD HH:mm Z", 7 | "watch": true, 8 | "watch_options": { 9 | "followSymlinks": true, 10 | "usePolling" : true, 11 | "interval" : 5 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /todolist.js: -------------------------------------------------------------------------------- 1 | /** 2 | IMPORTANT: This sample code is not production ready. It's only intended as an example of how validate Azure 3 | AD B2C bearer token (this part can be used in production environments). The to do list methods in this module: 4 | - Do NOT validate user input and query string parameters. 5 | - The global_todos is a global variable (local memory) without using lock mechanism. 6 | - The CORS settings allow ANY origin. 7 | - Some of the methods do NOT validate the caller ID. For example, the deleted method. 8 | - Never tested for security, performances and usability. 9 | **/ 10 | 11 | const express = require('express'); 12 | const morgan = require('morgan'); 13 | const passport = require('passport'); 14 | const config = require('./config.json') 15 | 16 | var router = express.Router(); 17 | 18 | const BearerStrategy = require('passport-azure-ad').BearerStrategy; 19 | 20 | const options = { 21 | identityMetadata: `https://${config.credentials.tenantName}.b2clogin.com/${config.credentials.tenantName}.onmicrosoft.com/${config.policies.policyName}/${config.metadata.version}/${config.metadata.discovery}`, 22 | clientID: config.credentials.clientID, 23 | audience: config.credentials.clientID, 24 | policyName: config.policies.policyName, 25 | isB2C: config.settings.isB2C, 26 | validateIssuer: config.settings.validateIssuer, 27 | loggingLevel: config.settings.loggingLevel, 28 | passReqToCallback: config.settings.passReqToCallback 29 | } 30 | 31 | const bearerStrategy = new BearerStrategy(options, (token, done) => { 32 | // Send user info using the second argument 33 | done(null, {}, token); 34 | } 35 | ); 36 | 37 | // Get the caller to do list. 38 | // GET: api/TodoItems 39 | router.get('/', 40 | passport.authenticate('oauth-bearer', { session: false }), 41 | (req, res) => { 42 | console.log('Validated claims: ', req.authInfo); 43 | 44 | // Get the caller to do list 45 | var todos = getCallerTodos(req); 46 | 47 | // Return the caller to do list 48 | res.status(200).json(todos); 49 | } 50 | ); 51 | 52 | // Get a single item from the caller to do list. 53 | // GET: api/TodoItems 54 | router.get('/*', 55 | passport.authenticate('oauth-bearer', { session: false }), 56 | (req, res) => { 57 | console.log('Validated claims: ', req.authInfo); 58 | 59 | // Get the caller to do list 60 | var todos = getCallerTodos(req); 61 | 62 | // Find the item by id from the caller to do list 63 | var item = todos.find(item => item.id === parseInt(req.params[0])); 64 | 65 | // Return the selected item 66 | res.status(200).json(item); 67 | } 68 | ); 69 | 70 | // Add a new item to the global to do list 71 | // POST: api/TodoItems 72 | router.post('/', passport.authenticate('oauth-bearer', { session: false }), 73 | (req, res) => { 74 | 75 | // Get the max ID from the global to do list 76 | var maxId = 1; 77 | if (global_todos.length > 0) 78 | maxId = Math.max.apply(Math, global_todos.map(function (item) { return item.id; })) + 1; 79 | 80 | // Create new item and add it to the global to do list 81 | var item = { "id": maxId, "owner": req.authInfo['sub'], "description": req.body.description, "status": false }; 82 | global_todos.push(item); 83 | 84 | // Return the new item 85 | res.status(200).json(item); 86 | } 87 | ); 88 | 89 | // Update an item 90 | // PUT: api/TodoItems/5 91 | router.put('/*', 92 | passport.authenticate('oauth-bearer', { session: false }), 93 | (req, res) => { 94 | console.log('Validated claims: ', req.authInfo); 95 | 96 | // Get the caller to do list 97 | var todos = getCallerTodos(req); 98 | 99 | // Find the item by id from the caller to do list 100 | var item = todos.find(item => item.id === parseInt(req.body.id)); 101 | item.description = req.body.description; 102 | item.status = req.body.status; 103 | 104 | // Return the selected item 105 | res.status(200).json(item); 106 | } 107 | ); 108 | 109 | // Delate an item 110 | // DELETE: api/TodoItems/5 111 | router.delete('/*', 112 | passport.authenticate('oauth-bearer', { session: false }), 113 | (req, res) => { 114 | console.log('Validated claims: ', req.authInfo); 115 | 116 | // Find the item by id from the global to do list 117 | var item = global_todos.find(item => item.id === parseInt(req.params[0])); 118 | 119 | // Find the item index in the global to do list 120 | let pos = global_todos.findIndex(item => item.id === parseInt(req.params[0])); 121 | 122 | // Remove the item from the global list 123 | global_todos.splice(pos, 1) 124 | 125 | // Return the selected item 126 | res.status(200).json(item); 127 | } 128 | ); 129 | 130 | // Return the caller items 131 | function getCallerTodos(req) { 132 | return global_todos.filter(item => item.owner === req.authInfo['sub']); 133 | } 134 | 135 | module.exports = router; 136 | --------------------------------------------------------------------------------