Skip to content

Latest commit

 

History

History
238 lines (173 loc) · 13.8 KB

File metadata and controls

238 lines (173 loc) · 13.8 KB

Vanilla JavaScript single-page application (SPA) using MSAL.js to authorize users for calling a protected web API on Azure AD B2C

  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

Overview

This sample demonstrates a Vanilla JavaScript single-page application that lets users authenticate against Azure Active Directory B2C using the Microsoft Authentication Library for JavaScript (MSAL.js), then acquires an Access Token for a web API that is also protected by Azure AD B2C. In doing so, it also illustrates various authorization and B2C concepts, such as Access Tokens, Refresh Tokens, Token Lifetimes and Configuration, silent requests and more.

Scenario

  1. The client application uses the MSAL.js to obtain an Access Token from Azure AD B2C.
  2. The Access Token is used as a bearer to authorize the user to call a protected web API.
  3. The protected web API responds with the claims in the Access Token.

Overview

Contents

File/folder Description
SPA/App/authPopup.js Main authentication logic resides here (using Popup flow).
SPA/App/authRedirect.js Use this instead of authPopup.js for authentication with redirect flow.
SPA/App/authConfig.js Contains configuration parameters for the sample.
SPA/App/policies.js Contains B2C custom policies and user-flows.
API/process.json Contains configuration parameters for logging via Morgan.
API/index.js Main application logic resides here.
API/config.json Contains authentication parameters for the sample.

Setup

Locate the sample folder API, then type:

    npm install

Locate the sample folder SPA, then type:

    npm install

Registration

ℹ️ 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 applications in the Azure Portal. Otherwise, continue with the steps for Running the sample.

Register the service app

  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 ms-identity-javascript-c3s2-api.
    • 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 access_as_user.
      • Select Admins and users options for Who can consent?
      • For Admin consent display name type Access ms-identity-javascript-c3s2-api
      • For Admin consent description type Allows the app to access ms-identity-javascript-c3s2-api as the signed-in user.
      • For User consent display name type Access ms-identity-javascript-c3s2-api
      • For User consent description type Allow the application to access ms-identity-javascript-c3s2-api 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 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 clientID and replace the existing value with the application ID (clientId) of the ms-identity-javascript-c3s2-api 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 ms-identity-javascript-c3s2-api application copied from the Azure portal.

Update the client app's registration

  1. Navigate to the Azure portal and select the Azure AD service.
  2. Select the App Registrations blade on the left, then find and select the application that you have registered in the previous tutorial (ms-identity-javascript-c1s2-spa).
  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 ms-identity-javascript-c3s2-spa.
    • Under Supported account types, select Accounts in any organizational directory or any identity provider. For authenticating users with Azure AD B2C.
    • In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URI: http://localhost:6420.
  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, 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 that you've just registered, i.e. ms-identity-javascript-c3s2-api.
    • 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.
    • Finally, click on the Grant admin consent button at the top.

Configure the client app 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".

Open the App\authConfig.js file. Then:

  1. Find the key msalConfig.auth.clientId and replace the existing value with the application ID (clientId) of the ms-identity-javascript-c1s2-spa application copied from the Azure portal.
  2. Find the key msalConfig.auth.redirectUri and replace the existing value with the base address of the ms-identity-javascript-c1s2-spa app (by default http://localhost:6420).
  3. Find the key apiConfig.scopes and replace the existing value with the scope of your web API (e.g. api://e767d418-b80b-4568-9754-557f40697fc5/access_as_user).
  4. Find the key apiConfig.uri and replace the existing value with the coordinates of your web API (by default http://localhost:5000).

Open the App\policies.js file. Then:

  1. Find the key b2cPolicies.names and populate it with your policy names e.g. signUpSignIn.
  2. Find the key b2cPolicies.authorities and populate it with your policy authority strings e.g. https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/b2c_1_susi.
  3. Find the key b2cPolicies.authorityDomain and populate it with the domain portion of your authority string e.g. <your-tenant-name>.b2clogin.com.

Running the sample

Locate the sample folder API, then type:

    npm start

Locate the sample folder SPA, then type:

    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:6420.
  2. Click on the sign-in button on the top right corner.
  3. Once you authenticate, click the Call API button at the center.

Screenshot

We'd love your feedback!

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

About the code

Acquire a Token

Access Token requests in MSAL.js are meant to be per-resource-per-scope(s). This means that an Access Token requested for resource A with scope scp1:

  • cannot be used for accessing resource A with scope scp2, and,
  • cannot be used for accessing resource B of any scope.

The intended recipient of an Access Token is represented by the aud claim; in case the value for the aud claim does not mach the resource APP ID URI, the token should be considered invalid. Likewise, the permissions that an Access Token grants is represented by the scp claim. See Access Token claims for more information.

MSAL.js exposes 3 APIs for acquiring a token: acquireTokenPopup(), acquireTokenRedirect() and acquireTokenSilent():

    myMSALObj.acquireTokenPopup(request)
        .then(response => {
            // do something with response
        })
        .catch(error => {
            console.log(error)
        });

For acquireTokenRedirect(), you must register a redirect promise handler:

    myMSALObj.handleRedirectPromise()
        .then(response => {
            // do something with response
        })
        .catch(error => {
            console.log(error);
        });

    myMSALObj.acquireTokenRedirect(request);

Token Validation

On the web API side, 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);
    );

Clients should treat access tokens as opaque strings, as the contents of the token are intended for the resource only (such as a web API or Microsoft Graph). For validation and debugging purposes, developers can decode JWTs (JSON Web Tokens) using a site like jwt.ms.

CORS Settings

For the purpose of the sample, cross-origin resource sharing is enabled for all domains. This is insecure. In production, you should modify this as to allow only the domains that you designate.

    app.use((req, res, next) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
        next();
    });

Next Tutorial

Continue with the next tutorial: Deploy your app to Azure.

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-ad azure-ad-b2c ms-identity 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.