Skip to content

Latest commit

 

History

History
329 lines (242 loc) · 17.2 KB

File metadata and controls

329 lines (242 loc) · 17.2 KB
page_type name description languages products urlFragment extensions
sample
React single-page application using MSAL React to authenticate users against Microsoft Entra External ID
React single-page application using MSAL React to authenticate users against Microsoft Entra External ID
javascript
entra-external-id
msal-react
ms-identity-ciam-javascript-tutorial-1-sign-in-react
services platform endpoint level client
ms-identity
javascript
AAD v2.0
100
React SPA

React single-page application using MSAL React to authenticate users against Microsoft Entra External ID

Overview

This sample demonstrates a React SPA that authenticates users against Microsoft Entra External ID, using the Microsoft Authentication Library for React (MSAL React).

MSAL React is a wrapper around the Microsoft Authentication Library for JavaScript (MSAL.js). As such, it exposes the same public APIs that MSAL.js offers, while adding many new features customized for modern React applications.

Here you'll learn how to sign-in users and acquire ID tokens.

Scenario

  1. The client React SPA uses the to sign-in a user and obtain a JWT ID Token from Microsoft Entra External ID.
  2. The ID Token proves that the user has successfully authenticated against Microsoft Entra External ID.

Scenario Image

Contents

File/folder Description
App.jsx Main application logic resides here.
NavigationBar.jsx Contains buttons for login and logout.
authConfig.js Contains authentication parameters.

Prerequisites

This sample will not work with a personal Microsoft account. If you're signed in to the Microsoft Entra admin center with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.

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-Authentication\1-sign-in-react\SPA
    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 Microsoft Entra 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. On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory

  2. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  3. Run the script to create your Azure AD application and configure the code of the sample application accordingly.

  4. 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 external 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 Microsoft Entra admin center.
  2. If your account is present in more than one external 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 external tenant.

Create User Flows

Please refer to: Tutorial: Create a sign-up and sign-in user flow

ℹ️ To enable password reset in an external tenant, please refer to: Tutorial: Enable users to unlock their account or reset passwords using Microsoft Entra self-service password reset

Add External Identity Providers

Please refer to:

Register the client app (msal-react-spa)

  1. Navigate to the Microsoft Entra admin center and select the Microsoft Entra External ID 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 msal-react-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 an external 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 (msal-react-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 SPA\src\authConfig.js file.
  2. Find the key Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of msal-react-spa app copied from the Microsoft Entra admin center.
  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-Authentication\1-sign-in-react\SPA
    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:3000.
  2. Select the Sign In button on the top right corner. Choose either Popup or Redirect flows (see: MSAL.js interaction types).

Screenshot

ℹ️ 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 node ms-identity adal msal-js msal].

To provide feedback on or suggest features for Microsoft Entra, visit User Voice page.

About the code

MSAL React should be instantiated outside of the component tree to prevent it from being re-instantiated on re-renders. After instantiation, pass it as props to your application.

import { createRoot } from 'react-dom/client';

const msalInstance = new PublicClientApplication(msalConfig);

const root = createRoot(document.getElementById('root'));
root.render(
    <App instance={msalInstance}/>
);

export default function App({msalInstance}) {

    return (
        <MsalProvider instance={msalInstance}>
            <PageLayout>
                <MainContent />
            </PageLayout>
        </MsalProvider>
    );
}

At the top of your component tree, wrap everything between MsalProvider component. All components underneath MsalProvider will have access to the PublicClientApplication instance via context as well as all hooks and components provided by msal-react.

export default function App({msalInstance}) {

    return (
        <MsalProvider instance={msalInstance}>
            <PageLayout>
                <MainContent />
            </PageLayout>
        </MsalProvider>
    );
}

Sign-in

MSAL.js exposes 3 login APIs: loginPopup(), loginRedirect() and ssoSilent(). These APIs are usable in MSAL React as well:

    export function App() {
        const { instance, accounts, inProgress } = useMsal();
    
        if (accounts.length > 0) {
            return <span>There are currently {accounts.length} users signed in!</span>
        } else if (inProgress === "login") {
            return <span>Login is currently in progress!</span>
        } else {
            return (
                <>
                    <span>There are currently no users signed in!</span>
                    <button onClick={() => instance.loginPopup()}>Login</button>
                </>
            );
        }
    }

You may also use MSAL React's useMsalAuthentication hook. Below is an example in which the ssoSilent() API is used. When using ssoSilent(), the recommended pattern is that you fallback to an interactive method should the silent SSO attempt fails:

function App() {
    const request = {
        loginHint: "name@example.com",
        scopes: ["User.Read"]
    }

    const { login, result, error } = useMsalAuthentication(InteractionType.Silent, request);

    useEffect(() => {
        if (error) {
            login(InteractionType.Popup, request);
        }
    }, [error]);

    const { accounts } = useMsal();

    return (
        <React.Fragment>
            <p>Anyone can see this paragraph.</p>
            <AuthenticatedTemplate>
                <p>Signed in as: {accounts[0]?.username}</p>
            </AuthenticatedTemplate>
            <UnauthenticatedTemplate>
                <p>No users are signed in!</p>
            </UnauthenticatedTemplate>
        </React.Fragment>
    );
}

As shown above, the components that depend on whether the user is authenticated should be wrapped inside React's AuthenticatedTemplate and UnauthenticatedTemplate components. Alternatively, you may use the useIsAuthenticated hook to conditionally render components.

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.

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