Skip to content

Latest commit

 

History

History
524 lines (394 loc) · 29.4 KB

File metadata and controls

524 lines (394 loc) · 29.4 KB
page_type name services languages products urlFragment description
sample
React single-page application using MSAL React to sign-in users and call Microsoft Graph API
ms-identity
javascript
react
azure-active-directory
ms-graph
msal-react
ms-identity-javascript-react-tutorial
This sample demonstrates a React single-page application that signs-in users with Azure AD and calls the using the Microsoft Authentication Library for React.

React single-page application using MSAL React to sign-in users and call Microsoft Graph API

Overview

This sample demonstrates a React single-page application (SPA) that signs-in users with Azure AD and calls the Microsoft Graph API using the Microsoft Authentication Library for React (MSAL React).

Here you'll learn how to sign-in, acquire a token and call a protected web API, as well as Dynamic Scopes and Incremental Consent, working with multiple resources and securing your routes and more.

ℹ️ See the community call: Deep dive on using MSAL.js to integrate React Single-page applications with Azure Active Directory

Scenario

  1. The client React SPA uses MSAL React to sign-in a user and obtain a JWT access token for Microsoft Graph API from Azure AD.
  2. The access token is used as a bearer token to authorize the user to call the Microsoft Graph API.
  3. The Microsoft Graph API responds with the payload if user is authorized.

Overview

Contents

File/folder Description
App.jsx Main application logic resides here.
fetch.jsx Provides a helper method for making fetch calls using bearer token scheme.
authConfig.js Contains authentication configuration parameters.
pages/Home.jsx Contains a table with ID token claims and description
pages/Profile.jsx Calls Microsoft Graph /me endpoint with Graph SDK.
pages/Contacts.jsx Calls Microsoft Graph /me/contacts endpoint with Graph SDK.
components/AccountPicker.jsx Contains logic to handle multiple account selection with MSAL.js

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. This sample uses ES6 conventions and will not run on Internet Explorer.
  • An Azure AD tenant. For more information, see: How to get an Azure AD tenant
  • A user account in your Azure AD tenant. This sample will not work with a personal Microsoft account. If you're signed in to the Azure portal 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-javascript-react-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 ms-identity-javascript-react-tutorial
    cd 2-Authorization-I\1-call-graph
    npm install

Developers who wish to increase their familiarity with programming for Microsoft Graph are advised to go through the An introduction to Microsoft Graph for developers recorded session.

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

Register the spa app (ms-identity-react-c2s1)

  1. Navigate to the Azure portal and select the Azure Active Directory 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 ms-identity-react-c2s1.
    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.html
    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.
  8. 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:
    1. Select the Add a permission button and then,
    2. Ensure that the Microsoft APIs tab is selected.
    3. In the Commonly used Microsoft APIs section, select Microsoft Graph
    4. In the Delegated permissions section, select the User.Read, Contacts.Read in the list. Use the search box if necessary.
    5. Select the Add permissions button at the bottom.
Configure the spa app (ms-identity-react-c2s1) 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 ms-identity-react-c2s1 app copied from the Azure portal.
  3. Find the key Enter_the_Tenant_Info_Here and replace the existing value with your Azure AD tenant ID.

Step 4: Running the sample

From your shell or command line, execute the following commands:

    cd  2-Authorization-I/1-call-graph/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.
  3. Select the Profile button on the navigation bar. This will make a call to the Graph API.
  4. Select the Contacts button on the navigation bar. This will make a call to the Graph API (:warning: the user needs to have an Office subscription for this call to work).

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. Make sure that your questions or comments are tagged with [azure-active-directory react ms-identity adal msal].

If you find a bug in the sample, raise the issue on GitHub Issues.

About the code

Protected resources and scopes

In order to access a protected resource on behalf of a signed-in user, the app needs to present a valid Access Token to that resource owner (in this case, Microsoft Graph). Access Token requests in MSAL 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 this case, it should be the Microsoft Graph API's App ID); in case the value for the aud claim does not mach the resource APP ID URI, the token will be considered invalid by the API. Likewise, the permissions that an Access Token grants are provided in the scp claim. See Access Token claims for more information.

Working with multiple resources

When you have to access multiple resources, initiate a separate token request for each:

    // "User.Read" stands as shorthand for "graph.microsoft.com/User.Read"
    const graphToken = await msalInstance.acquireTokenSilent({
         scopes: [ "User.Read" ]
    });
    const customApiToken = await msalInstance.acquireTokenSilent({
         scopes: [ "api://<myCustomApiClientId>/My.Scope" ]
    });

Bear in mind that you can request multiple scopes for the same resource (e.g. User.Read, User.Write and Calendar.Read for MS Graph API).

    const graphToken = await msalInstance.acquireTokenSilent({
         scopes: [ "User.Read", "User.Write", "Calendar.Read"] // all MS Graph API scopes
    });

In case you erroneously pass multiple resources in your token request, Azure AD will throw an exception, and your request will fail.

    // your request will fail for both resources
    const myToken = await msalInstance.acquireTokenSilent({
         scopes: [ "User.Read", "api://<myCustomApiClientId>/My.Scope" ]
    });

Dynamic scopes and incremental consent

In Azure AD, the scopes (permissions) set directly on the application registration are called static scopes. Other scopes that are only defined within the code are called dynamic scopes. This has implications on the login (i.e. loginPopup, loginRedirect) and acquireToken (i.e. acquireTokenPopup, acquireTokenRedirect, acquireTokenSilent) methods of MSAL.js. Consider:

     const loginRequest = {
          scopes: [ "openid", "profile", "User.Read" ]
     };

     const tokenRequest = {
          scopes: [ "Contacts.Read" ]
     };

     // will return an ID Token and an Access Token with scopes: "openid", "profile" and "User.Read"
     msalInstance.loginPopup(loginRequest);

     // will fail and fallback to an interactive method prompting a consent screen
     // after consent, the received token will be issued for "openid", "profile", "User.Read" and "Contacts.Read" combined
     msalInstance.acquireTokenPopup(tokenRequest);

In the code snippet above, the user will be prompted for consent once they authenticate and receive an ID Token and an Access Token with scope User.Read. Later, if they request an Access Token for User.Read, they will not be asked for consent again (in other words, they can acquire a token silently). On the other hand, the user did not consented to Contacts.Read at the authentication stage. As such, they will be asked for consent when requesting an Access Token for that scope. The token received will contain all the previously consented scopes, hence the term incremental consent. Read more on this topic at Scopes, permissions and consent in the Microsoft identity platform.

Acquire a Token

MSAL.js exposes 3 APIs for acquiring a token: acquireTokenPopup(), acquireTokenRedirect() and acquireTokenSilent(). MSAL React uses these APIs underneath, while offering developers higher level hooks and templates to simplify the token acquisition process:

    const { result, error, login } = useMsalAuthentication(InteractionType.Silent, {
        account: account,
        scopes: ["user.read"]
    });

    const [graphData, setGraphData] = useState(null);

    useEffect(() => {
        if (!!graphData) {
            return
        }

        if (!!error) {
            if (error instanceof InteractionRequiredAuthError) {
                login(InteractionType.Redirect, {
                    scopes: ["user.read"]
                });
            }
            console.log(error);
        }

        if (result) {
            const { accessToken } = result;

            // do something with the access token
        }
    }, [error, result, graphData]);

    return (
        <>
            {graphData ? <ProfileData graphData={graphData} /> : null}
        </>
    )

ℹ️ Please see the documentation on acquiring an access token to learn more about various methods available in MSAL.js to acquire tokens. For MSAL React in particular, see the useIsAuthenticated hook to learn more about useMsalAuthentication hook to acquire tokens.

Handle Continuous Access Evaluation (CAE) challenge from Microsoft Graph

Continuous access evaluation (CAE) enables applications to do just-in time token validation, for instance enforcing user session revocation in the case of password change/reset but there are other benefits. For details, see Continuous access evaluation.

Microsoft Graph is now CAE-enabled in Preview. This means that it can ask its client apps for more claims when conditional access policies require it. Your can enable your application to be ready to consume CAE-enabled APIs by:

  1. Declaring that the client app is capable of handling claims challenges.
  2. Processing these challenges when they are thrown by the web API

Declare the CAE capability in the configuration

This sample app declares that it's CAE-capable by adding the clientCapabilities property in the configuration in authConfig.js:

    const msalConfig = {
        auth: {
            clientId: 'Enter_the_Application_Id_Here', 
            authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here',
            redirectUri: "/", 
            postLogoutRedirectUri: "/",
            navigateToLoginRequestUrl: true, 
            clientCapabilities: ["CP1"] // this lets the resource owner know that this client is capable of handling claims challenge.
        }
    }

    const msalInstance = new PublicClientApplication(msalConfig);

Processing the CAE challenge from Microsoft Graph

Once the client app receives the CAE claims challenge from Microsoft Graph, it needs to present the user with a prompt for satisfying the challenge via Azure AD authorization endpoint. To do so, we use MSAL's useMsalAuthentication hook and provide the claims challenge as a parameter in the token request. This is shown in fetch.js, where we handle the response from the Microsoft Graph API with the handleClaimsChallenge method:

    const handleClaimsChallenge = async (response) => {
        if (response.status === 200) {
            return response.json();
        } else if (response.status === 401) {
            if (response.headers.get('www-authenticate')) {
                const account = msalInstance.getActiveAccount();
                const authenticateHeader = response.headers.get('www-authenticate');
                const claimsChallenge = parseChallenges(authenticateHeader);    

                /**
                 * This method stores the claim challenge to the session storage in the browser to be used when acquiring a token.
                 * To ensure that we are fetching the correct claim from the storage, we are using the clientId
                 * of the application and oid (user’s object id) as the key identifier of the claim with schema
                 * cc.<clientId>.<oid><resource.hostname>
                 */
                addClaimsToStorage(claimsChallenge, `cc.${msalConfig.auth.clientId}.${account.idTokenClaims.oid}`);
                return { error: 'claims_challenge_occurred', payload: claimsChallenge };
            }

            throw new Error(`Unauthorized: ${response.status}`);
        } else {
            throw new Error(`Something went wrong with the request: ${response.status}`);
        }
    };

After that, we require a new access token via the useMsalAuthentication hook, fetch the claims challenge from the browser's localStorage, and pass it to the useMsalAuthentication hook in the request parameter.

    export const Profile = () => {
        const { instance } = useMsal();
        const account = instance.getActiveAccount();
        const [graphData, setGraphData] = useState(null);
        const resource = new URL(protectedResources.graphMe.endpoint).hostname;
        const request = {
            scopes: protectedResources.graphMe.scopes,
            account: account,
            claims: account && getClaimsFromStorage(`cc.${msalConfig.auth.clientId}.${account.idTokenClaims.oid}.${resource}`)
                ? window.atob(getClaimsFromStorage(`cc.${msalConfig.auth.clientId}.${account.idTokenClaims.oid}.${resource}`))
                : undefined, // e.g {"access_token":{"xms_cc":{"values":["cp1"]}}}
        };

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

        useEffect(() => {
            if (!!graphData) {
                return;
            }

            if (!!error) {
                // in case popup is blocked, use redirect instead
                if (error.errorCode === "popup_window_error" || error.errorCode === "empty_window_error") {
                    login(InteractionType.Redirect, request);
                }

                console.log(error);
                return;
            }

            if (result) {
                fetchData(result.accessToken, protectedResources.graphMe.endpoint)
                    .then((response) => {
                        if (response && response.error) throw response.error;
                        setGraphData(response);
                    }).catch((error) => {
                        if (error === 'claims_challenge_occurred') {
                            login(InteractionType.Redirect, request);
                        }

                        console.log(error);
                    });
            }
        }, [graphData, result, error, login]);

        return (
            <>
                {graphData ? <ProfileData response={result} graphData={graphData} /> : null}
            </>
        );
    };

Access token validation

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.

For more details on what's inside the access token, clients should use the token response data that's returned with the access token to your client. When your client requests an access token, the Microsoft identity platform also returns some metadata about the access token for your app's consumption. This information includes the expiry time of the access token and the scopes for which it's valid. For more details about access tokens, please see Microsoft identity platform access tokens

Calling the Microsoft Graph API

Using the Fetch API, simply add the Authorization header to your request, followed by the access token you have obtained previously for this resource/endpoint (as a bearer token):

    export const callApiWithToken = async (accessToken, apiEndpoint) => {
        const headers = new Headers();
        const bearer = `Bearer ${accessToken}`;

        headers.append('Authorization', bearer);

        const options = {
            method: 'GET',
            headers: headers,
        };

        return fetch(apiEndpoint, options)
            .then((response) => handleClaimsChallenge(response))
            .catch((error) => error);
    };

Working with React routes

You can use React Router component in conjunction with MSAL React. Simply wrap the MsalProvider component between the Router component, passing the PublicClientApplication instance you have created earlier as props:

    const msalInstance = new PublicClientApplication(msalConfig);

    root.render(
        <React.StrictMode>
            <BrowserRouter>
                <App instance={msalInstance} />
            </BrowserRouter>
        </React.StrictMode>
    );

    export const App = ({ instance }) => {
        return (
            <MsalProvider instance={msalInstance}>
                <PageLayout>
                    <Pages />
                </PageLayout>
            </MsalProvider>
        );
    };

    const Pages = () => {
        return (
            <Routes>
                <Route path="/profile" element={<Profile />} />
                <Route path="/contacts" element={<Contacts />} />
                <Route path="/" element={<Home />} />
            </Routes>
        );
    };

MSAL logging

The Microsoft Authentication Library (MSAL) apps generate log messages to help diagnose issues. An app can configure logging with a few lines of code and have custom control over the level of detail and whether or not personal and organizational data is logged. Please check the authConfig.js file to see an example of configuring the logger with MSAL.js. For more information about using the logger with MSAL.js, see the following Logging in MSAL.js.

Next Steps

Learn how to:

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