AAD B2C- (4) Experience using AAD B2C to protect Node JS (passport.js)

This article demonstrates the following:


1. Deployed a Node JS WEB API, which is protected by AAD B2C (using Passport.js);

2. Use POSTMAN to simulate client requests, obtain access tokens from AAD B2C and initiate requests to the API;



1. Prepare the Node js API website, which is Microsoft sample code;

2. Add a new application for Node js API in AAD B2C and add the released scope;

3. Add an application for Postman in AAD B2C and authorize the application to the Node js API application;

4. Increase ROPC login user flow (user flow without browser);

5. Use the ROPC endpoint in Postman to obtain Access Token;

6. Access Node js API with Access Token in Postman;


Video introduction:

You can watch the video of this section at Station B: https://www.bilibili.com/video/BV1Cc411h7fM/


Graphic introduction:

This article uses sample code: https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi

Add a Node JS application:

Note that in this example, the reply URL is filled in: https: // localhost: 5000, this value is because our sample code is accessed through this url.

Fill in the ID URI "API" or other values.



Add the following two items to the published scope:

In this example, at least demo.read needs to be retained, because the sample code detects the string "demo.read".


As shown below, the code uses the "demo.read" string for permission detection. If you want to modify it, the published scope and code of the application in AAD B2C in Azure Portal need to be modified at the same time!



Next create the postmanclient application:



Set API access permissions to allow postmanclient access to APIs:



Modify the configuration file in the sample code:

In the video of this article, the detailed configuration explanation is made at 06:00 minutes, and how to find these values ​​is introduced;


For the user flow in the configuration, a new user flow of the ROPC type needs to be created. This type of user flow does not require a browser jump to log in to obtain the token:


According to the need, select the value that needs to be returned to the Token:



The sample code logic is as follows:

If there is "demo.read" in the user permission, the user name attribute is returned, otherwise, a 403 error is returned:



Start the website:


Access Token can be taken out according to the following parameters:

The following values ​​need to be modified according to the actual situation. The video of this article explains in detail about where each field can get the value from around 10:00



Use Token to request, the following figure can be successfully executed:



At the same time, we can get the user information in the Node JS code, and after getting the user information, we can integrate with the business logic:



At this point, this article is over!



Guess you like

Origin blog.51cto.com/10117438/2486636