Coder Social home page Coder Social logo

azure-samples / active-directory-b2c-javascript-nodejs-webapi Goto Github PK

View Code? Open in Web Editor NEW
141.0 50.0 88.0 189 KB

A small Node.js Web API for Azure AD B2C that shows how to protect your web api and accept B2C access tokens using Passport.js.

Home Page: http://aka.ms/aadb2c

License: MIT License

JavaScript 100.00%
microsoft identity azure-ad-b2c azure-active-directory javascript webapi

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

page_type languages products urlFragment description
sample
javascript
nodejs
ms-graph
azure-active-directory
azure-active-directory-b2c
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

  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. More information
  11. Community Help and Support
  12. Contributing

Overview

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:

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 B2C.
  2. The Access Token is used as a bearer token to authenticate the user when calling this web API.
  3. The web API responds with the name of the user obtained from the token claims.

Overview

Contents

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.

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

Setup

Step 1: Clone or download this repository

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.

Step 2: Install project dependencies

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

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

⚠️ 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.

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

Create User Flows and Custom Policies

Please refer to: Tutorial: Create user flows in Azure Active Directory B2C

Add External Identity Providers

Please refer to: Tutorial: Add identity providers to your applications in Azure Active Directory B2C

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

  1. Navigate to the Azure portal and select the Azure AD B2C 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-b2c-javascript-nodejs-webapi.
    • Under Supported account types, select Accounts in any 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 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.
  9. On the right side menu, select the Manifest blade.
    • Set accessTokenAcceptedVersion property to 2.
    • Click on Save.

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

  1. Open the config.json file.
  2. Find the key tenantName and replace the existing value with your Azure AD B2C tenant's name e.g. fabrikamb2c.
  3. 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.
  4. Find the key policyName and replace the existing value with name of the policy you've created, e.g. B2C_1_SUSI.

Running the sample

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

Explore the sample

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.

We'd love to hear from you

Consider taking a moment to share 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('/hello', passport.authenticate('oauth-bearer', { session: false }),
        (req, res) => {
            console.log('Validated claims: ', req.authInfo);
    );

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-b2c-javascript-nodejs-webapi's People

Contributors

carneirofc avatar danieldobalian avatar derisen avatar fdaugan avatar gsacavdm avatar imgbotapp avatar jennyf19 avatar jmprieur avatar kengaderdus avatar microsoftopensource avatar mmacy avatar msftgits avatar navyasric avatar parakhj avatar snyk-bot avatar supernova-eng avatar yoelhor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active-directory-b2c-javascript-nodejs-webapi's Issues

Unable to fetch metadata

Hi,

I am working on configuring passport-azure-ad to verify a JWT that is being send via a front-end service to my API. Unfortunately, I keep getting these errors:

Cannot get AAD Federation metadata from endpoint you specified https: ...

AND

authentication failed due to: In loadMetadata: Unable to fetch metadata

I followed the example here very closely and am using the exact BearerStrategy configuration options that were provided to me.

Has anyone else had this error?

Dependencies update required

                       === npm audit security report ===

# Run  npm install [email protected]  to resolve 1 vulnerability
SEMVER WARNING: Recommended action is a potentially breaking change

  Moderate        Out-of-bounds Read

  Package         base64url

  Dependency of   passport-azure-ad

  Path            passport-azure-ad > base64url

  More info       https://nodesecurity.io/advisories/658



found 1 moderate severity vulnerability in 258 scanned packages
  1 vulnerability requires semver-major dependency updates.

Screen shots of B2C configurations

Please can you add screen shots of the relevant bits of the Azure AD B2C application configurations for both the client and the API. In my opinion this example is useless as a worked example unless the reader can see what the settings are in Azure AD B2C.

Getting "In Strategy.prototype.jwtVerify: We did not pass Req back to Callback" when using express router

Please provide us with the following information:

This issue is for a: (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] question
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Cloned this repo to test Auth with passport-azure-ad, finally figured out what configuration would work with my apps and so far working well in the example code.

Tried to replicate the same thing for my existing application, which is using an express router instead of restify and path libraries.

my simple route:

router.get('/testToken', passport.authenticate('oauth-bearer', {
    session: false
}), (req, res, next) => {

    res.json({ msg: 'Auth actually worked!' });
    return next();
});

in the config, I have passReqToCallback: false
Getting

Any log messages given by the failure

Getting full VerifiedToken: blob and then:
{"name":"AzureAD: Bearer Strategy","hostname":"<host>","pid":115400,"level":30,"msg":"In Strategy.prototype.jwtVerify: We did not pass Req back to Callback","time":"2021-01-29T21:32:31.339Z","v":0}

In Postman I'm not getting any response after that, just keeps expecting it.

Expected/desired behavior

Browser and version?

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

Add Screenshots Of The Relevant B2C Config To The README

The README has links to 3 separate tutorials in order to configure this for yourself then it says to configure variables in the config.js based on those 3 tutorials.

Each tutorial is quite long and has lots of steps.

It would make things a lot clearer if you added screenshots of the Azure portal used in this demo for each of the 4 variables so there is something to compare against to make sure the right values are in the config file and are taken from the right place in the portal.

UPDATE:
The most useful screenshot would be of the Run Userflow https://docs.microsoft.com/en-ca/azure/active-directory-b2c/media/tutorial-create-user-flows/signup-signin-run-now.png

The part that says "Run user flow endpoint" has a url below it.
This is the url that the config.js is creating with those variables

const config = {
    identityMetadata: "https://" + b2cDomainHost + "/" + tenantId + "/" + policyName + "/v2.0/.well-known/openid-configuration/",
    clientID: clientID,
    policyName: policyName,
...
...

Highlighting this would be the easiest way for people to check that they have modified the sample correctly.

Broken README link for the frontend example

This issue is for a: (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] question
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

The README.md link JavaScript Single-page Application calling a custom Web API with MSAL.js 2.x using the auth code flow with PKCE is broken.

L34 Overview section of README.md

Maybe it's supposed to be this repo?

Minimal steps to reproduce

Acess https://github.com/Azure-Samples/ms-identity-javascript-callapi

Relevant B2C configurations

Hi,

I set up and run this nodejs webapi locally and have it called by the OpenIdConnect-DotNet-Core webapp sample. But unfortunately I always get the "authentication failed due to: token is not found" issue when click the API link. Attached API logs below. I believe this is related to some settings such as keys/scope/App ID URI and etc.

Would you mind providing details about how to configure the AAD B2C settings for the two applications (both the API and the webapp)?

{"name":"AzureAD: Bearer Strategy","hostname":"STLW10ASDC","pid":21300,"level":30,"msg":"In Strategy.prototype.authenticate: {"metadataURL":"https://login.microsoftonline.com/ttabe.onmicrosoft.com/v2.0/.well-known/openid-configuration/?x-client-SKU=passport-azure-ad&x-client-Ver=3.0.8&p=b2c_1_susi\",\"cacheKey\":\"https://login.microsoftonline.com/ttabe.onmicrosoft.com/v2.0/.well-known/openid-configuration/?x-client-SKU=passport-azure-ad&x-client-Ver=3.0.8&p=b2c_1_susi\"}","time":"2017-08-04T20:01:41.098Z","v":0}

{"name":"AzureAD: Bearer Strategy","hostname":"STLW10ASDC","pid":21300,"level":30,"msg":"In Strategy.prototype.authenticate: received metadata: {"url":"https://login.microsoftonline.com/ttabe.onmicrosoft.com/v2.0/.well-known/openid-configuration/?x-client-SKU=passport-azure-ad&x-client-Ver=3.0.8&p=b2c_1_susi\",\"metadata\":{\"issuer\":\"https://login.microsoftonline.com/ba272794-5cd2-4406-b1c1-c5f2d4553537/v2.0/\",\"authorization_endpoint\":\"https://login.microsoftonline.com/ttabe.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_susi\",\"token_endpoint\":\"https://login.microsoftonline.com/ttabe.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_susi\",\"end_session_endpoint\":\"https://login.microsoftonline.com/ttabe.onmicrosoft.com/oauth2/v2.0/logout?p=b2c_1_susi\",\"jwks_uri\":\"https://login.microsoftonline.com/ttabe.onmicrosoft.com/discovery/v2.0/keys?p=b2c_1_susi\",\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],\"response_types_supported\":[\"code\",\"id_token\",\"code id_token"],"scopes_supported":["openid"],"subject_types_supported":["pairwise"],"id_token_signing_alg_values_supported":["RS256"],"token_endpoint_auth_methods_supported":["client_secret_post"],"claims_supported":["oid","sub","newUser","postalCode","name","idp","tfp"]},"authtype":"oidc","oidc":{"algorithms":["RS256"],"authorization_endpoint":"https://login.microsoftonline.com/ttabe.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_susi\",\"end_session_endpoint\":\"https://login.microsoftonline.com/ttabe.onmicrosoft.com/oauth2/v2.0/logout?p=b2c_1_susi\",\"issuer\":\"https://login.microsoftonline.com/ba272794-5cd2-4406-b1c1-c5f2d4553537/v2.0/\",\"token_endpoint\":\"https://login.microsoftonline.com/ttabe.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_susi\",\"keys\":[{\"kid\":\"X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk\",\"nbf\":1493763266,\"use\":\"sig\",\"kty\":\"RSA\",\"e\":\"AQAB\",\"n\":\"tVKUtcx_n9rt5afY_2WFNvU6PlFMggCatsZ3l4RjKxH0jgdLq6CScb0P3ZGXYbPzXvmmLiWZizpb-h0qup5jznOvOr-Dhw9908584BSgC83YacjWNqEK3urxhyE2jWjwRm2N95WGgb5mzE5XmZIvkvyXnn7X8dvgFPF5QwIngGsDG8LyHuJWlaDhr_EPLMW4wHvH0zZCuRMARIJmmqiMy3VD4ftq4nS5s8vJL0pVSrkuNojtokp84AtkADCDU_BUhrc2sIgfnvZ03koCQRoZmWiHu86SuJZYkDFstVTVSR0hiXudFlfQ2rOhPlpObmku68lXw-7V-P7jwrQRFfQVXw\"}]}}","time":"2017-08-04T20:01:41.100Z","v":0}
{"name":"AzureAD: Bearer Strategy","hostname":"STLW10ASDC","pid":21300,"level":30,"msg":"In Strategy.prototype.authenticate: we will validate the following options: [object Object]","time":"2017-08-04T20:01:41.101Z","v":0}

{"name":"AzureAD: Bearer Strategy","hostname":"STLW10ASDC","pid":21300,"level":30,"msg":"authentication failed due to: token is not found","time":"2017-08-04T20:01:41.102Z","v":0}
GET /hello 401 5.397 ms - -

crashes if no scp claim passed

If you pass a token with no 'scp' claim, the app crashes with error
TypeError: Cannot read property 'split' of undefined

index.js row #54 should be
if ( 'scp' in claims && claims['scp'].split(" ").indexOf("demo.read") >= 0) {

Working with MFA

Hi,
I'm new with Azure AD B2C, and I try to use the web api with MFA.
I followed the all the tutorials, and I added a user that requires MFA authentication.
When I sign in with a "regular user", I'm getting a response from the api
image

But when I sign in with MFA user (same user flow), it opens a new dialog that always has a problem.
image

What am I doing wrong? Do I need to change something in the webapp/webapi?
Thanks

Cannot verify token

If validateIssuer set to true, following error is reported:
authentication failed due to: jwt issuer is invalid

What needs to happen to verify issuer?

[Azure Active Directory b2c] authentication failed due to: jwt audience is invalid

When I use the sample, all steps refer to this document.https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-single-page-app-webapi?tabs=app-reg-ga

An error occurred when I called the public API after logging in with my B2C account.

{"name":"AzureAD: Bearer Strategy","hostname":"jerry7","pid":1968,"level":30,"msg":"authentication failed due to: jwt audience is invalid","time":"2020-07-31T09:30:39.544Z","v":0}
GET /hello 401 5196.990 ms - -

This is the configuration of my web api sample.

const clientID = "9fe10508-405d-4617-8dee-52bca87e202f"; // Application (client) ID of your API's application registration
const b2cDomainHost = "poadevadb2c.b2clogin.com";
const tenantId = "poadevadb2c.onmicrosoft.com"; // Alternatively, you can use your Directory (tenant) ID (a GUID)
const policyName = "B2C_1_dpoa-b2c";

I'm sure all my Azure configurations are correct, but I can't figure out where the problem is.

Hope to get help, thanks

No user info data

Hi,

I got no error using the API and it is responding and logging the "Validated clams" information, but I have no user information in "req.user" attribute.
What can I configure to get the response?

Thank you

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.