Editja

Ixxerja permezz ta’


Tutorial: Create a React single-page application and prepare it for authentication

After registration is complete, a React project can be created using an integrated development environment (IDE). This tutorial demonstrates how to create a single-page React application using npm and create files needed for authentication and authorization.

In this tutorial:

  • Create a new React project
  • Configure the settings for the application
  • Install identity and bootstrap packages
  • Add authentication code to the application

Prerequisites

  • Completion of the prerequisites and steps in Tutorial: Register an application.
  • Although any IDE that supports React applications can be used, the following Visual Studio IDEs are used for this tutorial. They can be downloaded from the Downloads page. For macOS users, it's recommended to use Visual Studio Code.
    • Visual Studio 2022
    • Visual Studio Code
  • Node.js.

Create a new React project

Use the following tabs to create a React project within the IDE.

  1. Open Visual Studio, and then select Create a new project.

  2. Search for and choose the Standalone JavaScript React Project template, and then select Next.

  3. Enter a name for the project, such as reactspalocal.

  4. Choose a location for the project or accept the default option, and then select Next.

  5. In Additional information, select Create.

  6. From the toolbar, select Start Without Debugging to launch the application. A web browser will open with the address http://localhost:3000/ by default. The browser remains open and re-renders for every saved change.

  7. Create additional folders and files to achieve the following folder structure:

    ├─── public
    │   └─── index.html
    └───src
        ├─── components
        │   └─── PageLayout.jsx
        │   └─── ProfileData.jsx
        │   └─── SignInButton.jsx
        │   └─── SignOutButton.jsx
        └── App.css
        └── App.jsx
        └── authConfig.js
        └── graph.js
        └── index.css
        └── index.js
    

Install identity and bootstrap packages

Identity related npm packages must be installed in the project to enable user authentication. For project styling, Bootstrap will be used.

  1. In the Solution Explorer, right-click the npm option and select Install new npm packages.
  2. Search for @azure/MSAL-browser, then select Install Package. Repeat for @azure/MSAL-react.
  3. Search for and install react-bootstrap.
  4. Select Close.

To learn more about these packages refer to the documentation in msal-browser and msal-react.

Creating the authentication configuration file

  1. In the src folder, open authConfig.js and add the following code snippet:

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    
    import { LogLevel } from "@azure/msal-browser";
    
    /**
     * Configuration object to be passed to MSAL instance on creation. 
     * For a full list of MSAL.js configuration parameters, visit:
     * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md 
     */
    
    export const msalConfig = {
        auth: {
            clientId: "Enter_the_Application_Id_Here",
            authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
            redirectUri: "http://localhost:3000",
        },
        cache: {
            cacheLocation: "sessionStorage", // This configures where your cache will be stored
            storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
        },
        system: {	
            loggerOptions: {	
                loggerCallback: (level, message, containsPii) => {	
                    if (containsPii) {		
                        return;		
                    }		
                    switch (level) {
                        case LogLevel.Error:
                            console.error(message);
                            return;
                        case LogLevel.Info:
                            console.info(message);
                            return;
                        case LogLevel.Verbose:
                            console.debug(message);
                            return;
                        case LogLevel.Warning:
                            console.warn(message);
                            return;
                        default:
                            return;
                    }	
                }	
            }	
        }
    };
    
    /**
     * Scopes you add here will be prompted for user consent during sign-in.
     * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
     * For more information about OIDC scopes, visit: 
     * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
     */
    export const loginRequest = {
        scopes: ["User.Read"]
    };
    
    /**
     * Add here the scopes to request when obtaining an access token for MS Graph API. For more information, see:
     * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
     */
    export const graphConfig = {
        graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
    };
    
  2. Replace the following values with the values from the Microsoft Entra admin center.

    • clientId - The identifier of the application, also referred to as the client. Replace Enter_the_Application_Id_Here with the Application (client) ID value that was recorded earlier from the overview page of the registered application.
    • authority - This is composed of two parts:
      • The Instance is endpoint of the cloud provider. Check with the different available endpoints in National clouds.
      • The Tenant ID is the identifier of the tenant where the application is registered. Replace Enter_the_Tenant_Info_Here with the Directory (tenant) ID value that was recorded earlier from the overview page of the registered application.
  3. Save the file.

Modify index.js to include the authentication provider

All parts of the app that require authentication must be wrapped in the MsalProvider component. You instantiate a PublicClientApplication then pass it to MsalProvider.

  1. In the src folder, open index.js and replace the contents of the file with the following code snippet to use the msal packages and bootstrap styling:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    
    import { PublicClientApplication } from '@azure/msal-browser';
    import { MsalProvider } from '@azure/msal-react';
    import { msalConfig } from './authConfig';
    
    // Bootstrap components
    import 'bootstrap/dist/css/bootstrap.min.css';
    
    const msalInstance = new PublicClientApplication(msalConfig);
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    
    /**
     * We recommend wrapping most or all of your components in the MsalProvider component. It's best to render the MsalProvider as close to the root as possible.
     */
     root.render(
      <React.StrictMode>
          <MsalProvider instance={msalInstance}>
              <App />
          </MsalProvider>
      </React.StrictMode>
    );
    
  2. Save the file.

Next steps