Skip to content

Latest commit

 

History

History
325 lines (239 loc) · 18.6 KB

File metadata and controls

325 lines (239 loc) · 18.6 KB
page_type name description languages products urlFragment extensions
sample
Vanilla JavaScript single-page application using MSAL.js to authenticate users against Azure AD for Customers
This sample demonstrates a Vanilla JavaScript single-page application using MSAL.js to authenticate users against Azure Active Directory Customer Identity Access Management (Azure AD for Customers)
javascript
entra-external-id
msal-js
ms-identity-ciam-javascript-tutorial-0-sign-in-vanillajs
services platform endpoint level client
ms-identity
JavaScript
AAD v2.0
100
Vanilla JavaScript SPA

Vanilla JavaScript single-page application using MSAL.js to authenticate users against Azure AD for Customers

Overview

This sample demonstrates a vanilla JavaScript single-page application (SPA) that lets users authenticate to Azure Active Directory CIAM (Azure AD for Customers) using the Microsoft Authentication Library for JavaScript (MSAL.js). Here you'll learn about ID Tokens, OIDC scopes, single-sign on, silent requests and more.

Scenario

  1. The client JavaScript SPA uses the to sign-in a user and obtain a JWT ID Token from Azure AD for Customers.
  2. The ID Token proves that the user has successfully authenticated against Azure AD for Customers.

Scenario Image

Contents

File/folder Description
AppCreationScripts/ Contains Powershell scripts to automate app registration.
public/authPopup.js Main authentication logic resides here (using Popup flow).
public/authRedirect.js Use this instead of authPopup.js for authentication with redirect flow.
public/authConfig.js Contains configuration parameters for the sample.
public/ui.js Contains UI logic.
server.js Simple Express server for index.html.

Prerequisites

  • Node.js must be installed to run this sample.
  • 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.
  • A modern web browser.
  • An Azure AD for Customers tenant. For more information, see: How to get an Azure AD for Customers tenant
  • A user account with permissions to create applications in your Azure AD for Customers tenant.

Setup the sample

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git

or download and extract the repository .zip file.

⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.

Step 2: Install project dependencies

    cd 1-Authorization\0-sign-in-vanillajs\App
    npm install

Step 3: Register the sample application(s) in your tenant

There is one project in this sample. To register it, you can:

  • follow the steps below for manually register your apps
  • or use PowerShell scripts that:
    • automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
    • modify the projects' configuration files.
Expand this section if you want to use this automation:

⚠️ If you have never used Microsoft Graph PowerShell before, we recommend you go through the App Creation Scripts Guide once to ensure that your environment is prepared correctly for this step.

  1. Ensure that you have PowerShell 7 or later installed.

  2. Run the script to create your Azure AD application and configure the code of the sample application accordingly.

  3. For interactive process -in PowerShell, run:

    cd .\AppCreationScripts\
    .\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"

Other ways of running the scripts are described in App Creation Scripts guide. The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.

Choose the Azure AD for Customers tenant where you want to create your applications

To manually register the apps, 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 for Customers 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 for Customers tenant.

Create User Flows

Please refer to: Tutorial: Create user flow in Azure Active Directory CIAM

ℹ️ To enable password reset in Customer Identity Access Management (CIAM) in Azure Active Directory (Azure AD), please refer to: Tutorial: Enable self-service password reset

Add External Identity Providers

Please refer to:

Register the client app (ciam-msal-javascript-spa)

  1. Navigate to the Azure portal and select the Azure AD for Customers 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:
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example ciam-msal-javascript-spa.
    2. Under Supported account types, select Accounts in this organizational directory only
    3. Select Register to create the application.
  4. In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
  5. In the app's registration screen, select the Authentication blade to the left.
  6. If you don't have a platform added, select Add a platform and select the Single-page application option.
    1. In the Redirect URI section enter the following redirect URIs:
      1. http://localhost:3000
      2. http://localhost:3000/redirect
    2. Click Save to save your changes.
  7. Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
    1. In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs:
    2. Select the Add a permission button and then:
    3. Ensure that the Microsoft APIs tab is selected.
    4. In the Commonly used Microsoft APIs section, select Microsoft Graph
    5. In the Delegated permissions section, select openid, offline_access in the list. Use the search box if necessary.
    6. Select the Add permissions button at the bottom.
  8. At this stage, the permissions are assigned correctly, but since it's a CIAM tenant, the users themselves cannot consent to these permissions. To get around this problem, we'd let the tenant administrator consent on behalf of all users in the tenant. Select the Grant admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all accounts in the tenant. You need to be a tenant admin to be able to carry out this operation.
Configure the client app (ciam-msal-javascript-spa) 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 App\public\authConfig.js file.
  2. Find the key Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of ciam-msal-javascript-spa app copied from the Azure portal.
  3. Find the placeholder Enter_the_Tenant_Subdomain_Here and replace it with the Directory (tenant) subdomain. For instance, if your tenant primary domain is contoso.onmicrosoft.com, use contoso. If you don't have your tenant domain name, learn how to read your tenant details.

Step 4: Running the sample

    cd 1-Authorization\0-sign-in-vanillajs\App
    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:3000.
  2. Click the sign-in button on the top right corner.

ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.

We'd love your feedback!

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

Troubleshooting

Expand for troubleshooting info
  • 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. 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-b2c node ms-identity adal msal-js msal].

To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.

About the code

Sign-in

MSAL.js provides 3 login APIs: loginPopup(), loginRedirect() and ssoSilent():

    myMSALObj.loginPopup(loginRequest)
        .then((response) => {
            // your logic
        })
        .catch(error => {
            console.error(error);
        });

To use the redirect flow, you must register a handler for redirect promise. MSAL.js provideshandleRedirectPromise() API:

    myMSALObj.handleRedirectPromise()
        .then((response) => {
            // your logic
        })
        .catch(err => {
            console.error(err);
        });

    myMSALObj.loginRedirect(loginRequest);

The recommended pattern is that you fallback to an interactive method should the silent SSO fails.

    const silentRequest = {
      scopes: ["openid", "profile"],
      loginHint: "example@domain.net"
    };

    myMSALObj.ssoSilent(silentRequest)
        .then((response) => {
            // your logic
        }).catch(error => {
            console.error("Silent Error: " + error);
            if (error instanceof msal.InteractionRequiredAuthError) {
                myMSALObj.loginRedirect(loginRequest);
            }
        });

You can get all the active accounts of a user with the get getAllAccounts() API. If you know the username or home ID of an account, you can select it by:

    myMSALObj.getAccountByUsername(username);
    // or
    myMSALObj.getAccountByHomeId(homeId);

Sign-out

The Application redirects the user to the Microsoft identity platform logout endpoint to sign out. This endpoint clears the user's session from the browser. If your app did not go to the logout endpoint, the user may re-authenticate to your app without entering their credentials again, because they would have a valid single sign-in session with the Microsoft identity platform endpoint. For more, see: Send a sign-out request

ID Token Validation

When you receive an ID token directly from the IdP on a secure channel (e.g. HTTPS), such is the case with SPAs, there’s no need to validate it. If you were to do it, you would validate it by asking the same server that gave you the ID token to give you the keys needed to validate it, which renders it pointless, as if one is compromised so is the other.

Deploying SPA to Azure Storage

There is one single-page application in this sample. To deploy it to Azure Storage, you'll need to:

  • create an Azure Storage blob and obtain website coordinates
  • build your project and upload it to Azure Storage blob
  • update config files with website coordinates

ℹ️ If you would like to use VS Code Azure Tools extension for deployment, watch the tutorial offered by Microsoft Docs.

Build and upload (ciam-msal-javascript-spa) to an Azure Storage blob

ℹ️ If you don't have an account already, see: How to create a storage account.

  1. Sign in to the Azure portal.
  2. Locate your storage account and display the account overview.
  3. Select Static website to display the configuration page for static websites.
  4. Select Enabled to enable static website hosting for the storage account.
  5. In the Index document name field, specify a default index page (For example: index.html).
  6. The default index page is displayed when a user navigates to the root of your static website.
  7. Select Save. The Azure portal now displays your static website endpoint. Make a note of the Primary endpoint field.
  8. In the ciam-msal-javascript-spa project source code, update your configuration file with the Primary endpoint field as your new Redirect URI (you will register this URI later).
  9. Next, select Storage Explorer.
  10. Expand the BLOB CONTAINERS node, and then select the $web container.
  11. Choose the Upload button to upload files.
  12. If you intend for the browser to display the contents of file, make sure that the content type of that file is set to text/html.
  13. In the pane that appears beside the account overview page of your storage account, select Static Website. The URL of your site appears in the Primary endpoint field. In the next section, you will register this URI.

Update the CIAM app registration for ciam-msal-javascript-spa

  1. Navigate back to to the Azure portal.
  2. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations.
  3. In the resulting screen, select ciam-msal-javascript-spa.
  4. In the app's registration screen, select Authentication in the menu.
    1. In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
      1. https://ciam-msal-javascript-spa.azurewebsites.net/
      2. https://ciam-msal-javascript-spa.azurewebsites.net/redirect

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 opencode@microsoft.com with any additional questions or comments.

Learn More