Site icon Rajeev Singh | Coder, Blogger, YouTuber

Sign in users in a single-page app (SPA) and call the Microsoft Graph API using React

Overview:

This post uses a sample React single-page app (SPA) to show you how to sign in users by using the authorization code flow with Proof Key for Code Exchange (PKCE). It uses the Microsoft Authentication Library for JavaScript to handle authentication.

Protocol details

The OAuth 2.0 authorization code flow is described in section 4.1 of the OAuth 2.0 specification. Apps using the OAuth 2.0 authorization code flow acquire an access_token to include in requests to resources protected by the Microsoft identity platform (typically APIs). Apps can also request new ID and access tokens for previously authenticated entities by using a refresh mechanism.

This diagram shows a high-level view of the authentication flow:

Redirect URIs for single-page apps (SPAs)

Redirect URIs for SPAs that use the auth code flow require special configuration.

The spa redirect type is backward-compatible with the implicit flow. Apps currently using the implicit flow to get tokens can move to the spa redirect URI type without issues and continue using the implicit flow.

Redirect URI: MSAL.js 2.0 with auth code flow

Follow these steps to add a redirect URI for an app that uses MSAL.js 2.0 or later. MSAL.js 2.0+ supports the authorization code flow with PKCE and CORS in response to browser third party cookie restrictions. The implicit grant flow is not supported in MSAL.js 2.0+.

  1. In the Microsoft Entra admin center, select the app registration you created earlier in Create the app registration.
  2. Under Manage, select Authentication > Add a platform.
  3. Under Web applications, select the Single-page application tile.
  4. Under Redirect URIs, enter a redirect URI. Do NOT select either checkbox under Implicit grant and hybrid flows.
  5. Select Configure to finish adding the redirect URI.

You’ve now completed the registration of your single-page application (SPA) and configured a redirect URI to which the client will be redirected and any security tokens will be sent. By configuring your redirect URI using the Single-page application tile in the Add a platform pane, your application registration is configured to support the authorization code flow with PKCE and CORS.

Demo

Prerequisites

Demo (Summary);

  1. Register the application and record identifiers
  2. Add a platform redirect URI
  3. Clone or download the sample application
  4. Configure the project
  5. Run the application and sign in
  6. Validate

Demo(Step-by-step)

Register the application and record identifiers

To complete registration, provide the application a name, specify the supported account types, and add a redirect URI. Once registered, the application Overview pane displays the identifiers needed in the application source code.

  1. Sign in to the Microsoft Entra admin center.
  2. If you have access to multiple tenants, use the Settings icon   in the top menu to switch to the tenant in which you want to register the application from the Directories + subscriptions menu.
  3. Browse to Identity > Applications > App registrations, select New registration.
  4. Enter a Name for the application, such as identity-client-spa.
  5. For Supported account types, select Accounts in this organizational directory only. For information on different account types, select the Help me choose option.
  6. Select Register.

 Note

The Supported account types can be changed by referring to Modify the accounts supported by an application.

Add a platform redirect URI

To specify your app type to your app registration, follow these steps:

  1. Under Manage, select Authentication.
  2. On the Platform configurations page, select Add a platform, and then select SPA option.
  3. For the Redirect URIs enter http://localhost:3000.
  4. Select Configure to save your changes.

Clone or download the sample application

To obtain the sample application, you can either clone it from GitHub or download it as a .zip file.

git clone https://github.com/Azure-Samples/ms-identity-docs-code-javascript.git

Configure the project

  1. In your IDE, open the project folder, ms-identity-docs-code-javascript/react-spa, containing the sample.
  2. Open src/authConfig.js and update the following values with the information recorded earlier in the admin center.

JavaScript

JavaScript
/*
 * 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",
};



Run the application and sign in

Run the project with a web server by using Node.js:

  1. To start the server, run the following commands from within the project directory:
npm install

npm start

Conclusion

In summary, this post provides developers with a practical guide to implementing secure sign-in functionality in React SPAs using the Microsoft identity platform. By following the steps outlined in the post, you can enhance your application’s security and seamlessly integrate with Microsoft Graph services.

Happy coding!

🚀🔐👨‍💻

 

References:

Quickstart: Sign in to a SPA & call an API – React – Microsoft identity platform | Microsoft Learn

Tutorial: Call an API from a React single-page app – Microsoft identity platform | Microsoft Learn

Exit mobile version