Skip to content

Commit fbb2947

Browse files
committed
refactoring
1 parent 47b77d5 commit fbb2947

File tree

9 files changed

+241
-73
lines changed

9 files changed

+241
-73
lines changed

CHANGELOG.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# CHANGELOG
2+
3+
## 3/04/2020
4+
5+
* Dependencies updated.
6+
* Configuration parameters separated.
7+
* Readme improved.
8+
* ES6 conventions introduced.

CODE_OF_CONDUCT.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
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

CONTRIBUTING.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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`

LICENSE copy

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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

README.md

Lines changed: 90 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,118 @@
11
---
22
page_type: sample
3-
description: "This sample demonstrates how to protect a Node.js web API with Azure AD B2C using the Passport.js library."
43
languages:
54
- javascript
6-
- nodejs
5+
- node.js
76
products:
8-
- azure
9-
- azure-active-directory
10-
urlFragment: nodejs-web-api-azure-ad
7+
- microsoft-identity-platform
8+
- azure-active-directory-b2c
9+
description: "A sample demonstrating how to protect a Node.js web API with Azure AD B2C using the Passport.js library."
10+
urlFragment: "active-directory-b2c-javascript-nodejs-webapi"
1111
---
1212

13-
1413
# Node.js Web API with Azure AD B2C
1514

1615
This sample demonstrates how to protect a Node.js web API with Azure AD B2C using the Passport.js library. The code here is pre-configured with a registered client ID. If you register your own app, you will need to replace the client ID.
1716

18-
We have deployed this API to Azure to allow testing without running it locally. Checkout one of the apps in [Next Steps](https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi/blob/master/README.md#next-steps) to use it!
17+
To see how to call this web API from a client application, refer to this [B2C Single Page Application sample](https://github.com/Azure-Samples/active-directory-b2c-javascript-msal-singlepageapp).
18+
19+
## Contents
20+
21+
| File/folder | Description |
22+
|-------------------|--------------------------------------------|
23+
| `process.json` | Contains configuration parameters for logging via Morgan. |
24+
| `index.js` | Main application logic resides here. |
25+
| `apiConfig.js` | Contains configuration parameters for the sample. |
26+
| `.gitignore` | Defines what to ignore at commit time. |
27+
| `CHANGELOG.md` | List of changes to the sample. |
28+
| `CODE_OF_CONDUCT.md` | Code of Conduct information. |
29+
| `CONTRIBUTING.md` | Guidelines for contributing to the sample. |
30+
| `LICENSE` | The license for the sample. |
31+
| `package.json` | Package manifest for npm. |
32+
| `README.md` | This README file. |
33+
| `SECURITY.md` | Security disclosures. |
34+
| `server.js` | Implements a simple Node server to api endpoint(s). |
1935

2036
## Steps to Run
2137

2238
1. Clone the code.
2339

24-
```bash
25-
git clone https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi
26-
```
40+
```console
41+
git clone https://github.com/Azure-Samples/active-directory-javascript-nodejs-webapi-v2
42+
```
43+
44+
2. Make sure you've installed [Node.js](https://nodejs.org/en/download/).
45+
46+
3. Install the node dependencies:
2747

28-
2. Make sure you've [installed Node](https://nodejs.org/en/download/).
48+
```console
49+
npm install && npm update
50+
```
2951

30-
4. Install the node dependencies:
52+
4. Run the Web API! By default it will run on `http://localhost:5000`
3153

32-
```bash
33-
npm install && npm update
34-
```
35-
5. Run the Web API! By default it will run on `http://localhost:5000`.
36-
```bash
37-
node index.js
38-
```
54+
```console
55+
npm start
56+
```
3957

4058
## Next Steps
41-
The `/hello` endpoint in this sample is protected so an authorized request to it requires an access token in the header.
42-
You can make authorized requests to this web API using an [iOS App](https://github.com/Azure-Samples/active-directory-b2c-ios-swift-native-msal) or [Android App](https://github.com/Azure-Samples/active-directory-b2c-android-native-msal). Make sure to update the app configs if you want it to point to your local hello api.
4359

44-
Alternatively, you can [register your own app](https://apps.dev.microsoft.com) and point to this web API.
60+
### Using your own Azure AD B2C Tenant
61+
62+
To have a proper understanding of Azure AD B2C as a developer, follow the tutorials on Azure [AD B2C documentation](https://docs.microsoft.com/en-us/azure/active-directory-b2c/). In the rest of this guide, we summarize the steps you need to go through.
63+
64+
#### Step 1: Get your own Azure AD B2C Tenant
65+
66+
First, you'll need an Azure AD B2C tenant. If you don't have an existing Azure AD B2C tenant that you can use for testing purposes, you can create your own by following [these instructions](https://azure.microsoft.com/documentation/articles/active-directory-b2c-get-started).
67+
68+
#### Step 2: Create your own policies
69+
70+
This sample uses a unified sign-up/sign-in policy. You can create [your own unified sign-up/sign-in policy](https://azure.microsoft.com/documentation/articles/active-directory-b2c-reference-policies). You may choose to include as many or as few identity providers as you wish.
71+
72+
If you already have existing policies in your Azure AD B2C tenant, feel free to re-use those policies in this sample.
73+
74+
#### Step 3: Register your own web API with Azure AD B2C
4575

46-
Customize your user experience further by supporting more identity providers. Checkout the docs belows to learn how to add additional providers:
76+
Follow the instructions at [register a Web API with Azure AD B2C](https://docs.microsoft.com/en-us/azure/active-directory-b2c/add-web-application?tabs=applications) to register the Node.js Web API sample with your tenant. Registering your Web API allows you to define the scopes that your single page application will request access tokens for.
4777

48-
- [Microsoft](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-setup-msa-app)
49-
- [Facebook](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-setup-fb-app)
50-
- [Google](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-setup-goog-app)
51-
- [Amazon](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-setup-amzn-app)
52-
- [LinkedIn](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-setup-li-app)
78+
#### Step 4: Configure your application source code
5379

80+
You can now fill in the variables in the `apiConfig.js` file of the Node.js Web API sample with the parameters you've obtained from the Azure Portal during the steps above.
81+
82+
Configure the following variables:
83+
84+
```javascript
85+
const clientID = "<Application ID for your Node.js Web API - found on Properties page in Azure portal e.g. 93733604-cc77-4a3c-a604-87084dd55348>";
86+
const b2cDomainHost = "<Domain of your B2C host eg. fabrikamb2c.b2clogin.com>";
87+
const tenantIdGuid = "<Application ID for your Node.js Web API - found on Properties page in Azure portal e.g. 775527ff-9a37-4307-8b3d-cc311f58d925>";
88+
const policyName = "<Name of your sign in / sign up policy, e.g. B2C_1_SUSI>";
89+
```
90+
91+
> **NOTE**
92+
>
93+
>Developers using the [Azure China Environment](https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-national-cloud), MUST use <your-tenant-name>.b2clogin.cn authority, instead of `login.chinacloudapi.cn`.
94+
>
95+
> In order to use <your-tenant-name>.b2clogin.*, you will need to configure you application and set `validateAuthority: false`. Learn more about using [b2clogin](https://docs.microsoft.com/en-us/azure/active-directory-b2c/b2clogin#set-the-validateauthority-property).
96+
97+
Lastly, to run your Node.js Web API, run the following command from your shell or command line
98+
99+
```bash
100+
npm install && npm update
101+
npm start
102+
```
103+
104+
Your Node.js Web API sample is now running on Port 5000.
54105

55106
## Questions & Issues
56107

57-
Please file any questions or problems with the sample as a GitHub issue. You can also post on Stack Overflow with the tag `azure-ad-b2c`. For OAuth2.0 library issues, please see note below.
108+
Please file any questions or problems with the sample as a GitHub issue. You can also post on Stack Overflow with the tag `azure-ad-b2c`. For OAuth2.0 library issues, please see note below.
109+
110+
## Contributing
111+
112+
If you'd like to contribute to this sample, see [CONTRIBUTING.MD](./CONTRIBUTING.md).
113+
114+
## Code of Conduct
115+
116+
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
117+
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
118+
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

SECURITY.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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).

apiConfig.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Update these four variables with your values from the B2C portal
2+
const clientID = "93733604-cc77-4a3c-a604-87084dd55348";
3+
const b2cDomainHost = "fabrikamb2c.b2clogin.com";
4+
const tenantIdGuid = "775527ff-9a37-4307-8b3d-cc311f58d925"; // alternatively, you can use your tenant name as well
5+
const policyName = "B2C_1_SUSI";
6+
7+
const config = {
8+
identityMetadata: "https://" + b2cDomainHost + "/" + tenantIdGuid + "/" + policyName + "/v2.0/.well-known/openid-configuration/",
9+
clientID: clientID,
10+
policyName: policyName,
11+
isB2C: true,
12+
validateIssuer: false,
13+
loggingLevel: 'info',
14+
loggingNoPII: false,
15+
passReqToCallback: false
16+
}
17+
18+
module.exports = config;

index.js

Lines changed: 26 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,55 @@
1-
// Authors:
2-
// Shane Oatman https://github.com/shoatman
3-
// Sunil Bandla https://github.com/sunilbandla
4-
// Daniel Dobalian https://github.com/danieldobalian
5-
6-
var express = require("express");
7-
var morgan = require("morgan");
8-
var passport = require("passport");
9-
var BearerStrategy = require('passport-azure-ad').BearerStrategy;
10-
11-
/* Update these four variables with your values from the B2C portal */
12-
var clientID = "93733604-cc77-4a3c-a604-87084dd55348";
13-
var b2cDomainHost = "fabrikamb2c.b2clogin.com";
14-
var tenantIdGuid = "775527ff-9a37-4307-8b3d-cc311f58d925";
15-
var policyName = "B2C_1_SUSI";
16-
17-
18-
var options = {
19-
identityMetadata: "https://" + b2cDomainHost + "/" + tenantIdGuid + "/" + policyName + "/v2.0/.well-known/openid-configuration/",
20-
21-
clientID: clientID,
22-
policyName: policyName,
23-
isB2C: true,
24-
validateIssuer: false,
25-
loggingLevel: 'info',
26-
loggingNoPII: false,
27-
passReqToCallback: false
28-
};
29-
30-
var bearerStrategy = new BearerStrategy(options,
1+
const express = require("express");
2+
const morgan = require("morgan");
3+
const passport = require("passport");
4+
const config = require('./apiConfig');
5+
const BearerStrategy = require('passport-azure-ad').BearerStrategy;
6+
7+
// A simple check for clientID placeholder
8+
if (config.clientID === 'YOUR_CLIENT_ID') {
9+
console.error("Please update 'options' with the client id (application id) of your application");
10+
return;
11+
}
12+
13+
const bearerStrategy = new BearerStrategy(config,
3114
function (token, done) {
3215
// Send user info using the second argument
3316
done(null, {}, token);
3417
}
3518
);
3619

37-
var app = express();
38-
app.use(morgan('dev'));
20+
const app = express();
3921

22+
app.use(morgan('dev'));
4023
app.use(passport.initialize());
24+
4125
passport.use(bearerStrategy);
4226

43-
app.use(function (req, res, next) {
27+
//enable CORS
28+
app.use((req, res, next) => {
4429
res.header("Access-Control-Allow-Origin", "*");
4530
res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
4631
next();
4732
});
4833

34+
// API endpoint
4935
app.get("/hello",
5036
passport.authenticate('oauth-bearer', {session: false}),
51-
function (req, res) {
52-
var claims = req.authInfo;
37+
(req, res) => {
5338
console.log('User info: ', req.user);
54-
console.log('Validated claims: ', claims);
39+
console.log('Validated claims: ', req.authInfo);
5540

56-
if (claims['scp'].split(" ").indexOf("demo.read") >= 0) {
41+
if (req.authInfo['scp'].split(" ").indexOf("demo.read") >= 0) {
5742
// Service relies on the name claim.
58-
res.status(200).json({'name': claims['name']});
43+
res.status(200).json({'name': req.authInfo['name']});
5944
} else {
6045
console.log("Invalid Scope, 403");
6146
res.status(403).json({'error': 'insufficient_scope'});
6247
}
6348
}
6449
);
6550

66-
var port = process.env.PORT || 5000;
67-
app.listen(port, function () {
51+
const port = process.env.PORT || 5000;
52+
53+
app.listen(port, () => {
6854
console.log("Listening on port " + port);
6955
});

0 commit comments

Comments
 (0)