Muokkaa

Jaa


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

In this quickstart, you use a sample 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) and call the Microsoft Graph API. The sample uses the Microsoft Authentication Library to handle authentication.

Prerequisites

  • An Azure account with an active subscription. If you don't already have one, Create an account for free.
  • This Azure account must have permissions to manage applications. Any of the following Microsoft Entra roles include the required permissions:
    • Application Administrator
    • Application Developer
    • Cloud Application Administrator.
  • Node.js.
  • Visual Studio Code or another code editor.

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.

    Screenshot that shows how to enter a name and select the account type in the Microsoft Entra admin center.

  7. The application's Overview pane is displayed when registration is complete. Record the Directory (tenant) ID and the Application (client) ID to be used in your application source code.

    Screenshot that shows the identifier values on the overview page on the Microsoft Entra admin center.

    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.

  • To clone the sample, open a command prompt and navigate to where you wish to create the project, and enter the following command:

    git clone https://github.com/Azure-Samples/ms-identity-docs-code-javascript.git
    
  • Download the .zip file. Extract it to a file path where the length of the name is fewer than 260 characters.

Configure the project

  1. In your IDE, open the project folder, ms-identity-docs-code-javascript, containing the sample.

  2. Open vanillajs-spa/App/public/authConfig.js and update the following values with the information recorded in the admin center.

    /**
     * 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 
     */
    const msalConfig = {
        auth: {
    
             // WORKFORCE TENANT
             authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here", //  Replace the placeholder with your tenant info
             // EXTERNAL TENANT
             // authority: "https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/", // Replace the placeholder with your tenant subdomain
            redirectUri: '/', // You must register this URI on App Registration. Defaults to window.location.href e.g. http://localhost:3000/
            navigateToLoginRequestUrl: true, // If "true", will navigate back to the original request location before processing the auth code response.
        },
        cache: {
            cacheLocation: 'sessionStorage', // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO.
            storeAuthStateInCookie: false, // set this to true if you have to support IE
        },
        system: {
            loggerOptions: {
                loggerCallback: (level, message, containsPii) => {
                    if (containsPii) {
                        return;
                    }
                    switch (level) {
                        case msal.LogLevel.Error:
                            console.error(message);
                            return;
                        case msal.LogLevel.Info:
                            console.info(message);
                            return;
                        case msal.LogLevel.Verbose:
                            console.debug(message);
                            return;
                        case msal.LogLevel.Warning:
                            console.warn(message);
                            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://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview#openid-connect-scopes
     * https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview#openid-connect-scopes
     */
    const loginRequest = {
        scopes: ["User.Read"],
    };
    
    /**
     * An optional silentRequest object can be used to achieve silent SSO
     * between applications by providing a "login_hint" property.
     */
    
    // const silentRequest = {
    //   scopes: ["openid", "profile"],
    //   loginHint: "example@domain.net"
    // };
    
    // exporting config object for jest
    if (typeof exports !== 'undefined') {
        module.exports = {
            msalConfig: msalConfig,
            loginRequest: loginRequest,
        };
        module.exports = {
            msalConfig: msalConfig,
            loginRequest: loginRequest,
        };
    }
    
    • clientId - The identifier of the application, also referred to as the client. Replace the text in quotes with the Application (client) ID value that was recorded earlier.
    • authority - The authority is a URL that indicates a directory that MSAL can request tokens from. Replace Enter_the_Tenant_Info_Here with the Directory (tenant) ID value that was recorded earlier.
    • redirectUri - The Redirect URI of the application. If necessary, replace the text in quotes with the redirect URI that was recorded earlier.

Run the application and sign in and sign out

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:

    cd vanillajs-spa/App
    npm install
    npm start
    
  2. Copy the https URL that appears in the terminal, for example, https://localhost:3000, and paste it into a browser. We recommend using a private or incognito browser session.

  3. Follow the steps and enter the necessary details to sign in with your Microsoft account. You'll be requested an email address so a one time passcode can be sent to you. Enter the code when prompted.

  4. The application will request permission to maintain access to data you have given it access to, and to sign you in and read your profile. Select Accept. The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.

    Screenshot of JavaScript App depicting the results of the API call.

Prerequisites

  • An external tenant. To create one, choose from the following methods:
  • This Azure account must have permissions to manage applications. Any of the following Microsoft Entra roles include the required permissions:
    • Application Administrator
    • Application Developer
    • Cloud Application Administrator.
  • Node.js.
  • Visual Studio Code or another code editor.

Register the application and record identifiers

To enable your application to sign in users with Microsoft Entra, Microsoft Entra External ID must be made aware of the application you create. The app registration establishes a trust relationship between the app and Microsoft Entra. When you register an application, External ID generates a unique identifier known as an Application (client) ID, a value used to identify your app when creating authentication requests.

The following steps show you how to register your app in the Microsoft Entra admin center:

  1. Sign in to the Microsoft Entra admin center as at least an Application Developer.

  2. If you have access to multiple tenants, use the Settings icon in the top menu to switch to your external tenant from the Directories + subscriptions menu.

  3. Browse to Identity >Applications > App registrations.

  4. Select + New registration.

  5. In the Register an application page that appears;

    1. Enter a meaningful application Name that is displayed to users of the app, for example ciam-client-app.
    2. Under Supported account types, select Accounts in this organizational directory only.
  6. Select Register.

  7. The application's Overview pane displays upon successful registration. Record the Application (client) ID to be used in your application source code.

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.

Once you register your application, it gets assigned the User.Read permission. However, since the tenant is an external tenant, the customer users themselves can't consent to this permission. You as the tenant administrator must consent to this permission on behalf of all the users in the tenant:

  1. From the App registrations page, select the application that you created (such as ciam-client-app) to open its Overview page.

  2. Under Manage, select API permissions.

    1. Select Grant admin consent for <your tenant name>, then select Yes.
    2. Select Refresh, then verify that Granted for <your tenant name> appears under Status for the permission.

Create a user flow

For the customer users to see the sign-up or sign-in experience when they use your app, you need to associate your app with a user flow. Although many applications can be associated with your user flow, a single application can only be associated with one user flow.

  1. On the sidebar menu, select Identity.

  2. Select External Identities, then User flows.

  3. In the User flows page, select the User flow name you created earlier, for example, SignInSignUpSample.

  4. Under Use, select Applications.

  5. Select Add application.

  6. Select the application from the list such as ciam-client-app or use the search box to find the application, and then select it.

  7. Choose Select.

Once you associate your app with a user flow, you can test your user flow by simulating a user’s sign-up or sign-in experience with your application from within the Microsoft Entra admin center. To do so, use the steps in Test your sign-up and sign-in user flow.

Associate the SPA with the user flow

For the customer users to see the sign-up or sign-in experience when they use your app, you need to associate your app with a user flow. Although many applications can be associated with your user flow, a single application can only be associated with one user flow.

  1. On the sidebar menu, select Identity.

  2. Select External Identities, then User flows.

  3. In the User flows page, select the User flow name you created earlier, for example, SignInSignUpSample.

  4. Under Use, select Applications.

  5. Select Add application.

  6. Select the application from the list such as ciam-client-app or use the search box to find the application, and then select it.

  7. Choose Select.

Once you associate your app with a user flow, you can test your user flow by simulating a user’s sign-up or sign-in experience with your application from within the Microsoft Entra admin center. To do so, use the steps in Test your sign-up and sign-in user flow.

Clone or download sample SPA

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

  • To clone the sample, open a command prompt and navigate to where you wish to create the project, and enter the following command:

    git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git
    
  • Download the sample. Extract it to a file path where the length of the name is fewer than 260 characters.

Configure the sample SPA

  1. Open App/public/authConfig.js and replace the following with the values obtained from the Microsoft Entra admin center:

    • Enter_the_Application_Id_Here and replace it with the Application (client) ID of the app you registered earlier.
    • Enter_the_Tenant_Subdomain_Here and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is contoso.onmicrosoft.com, use contoso. If you don't have your tenant name, learn how to read your tenant details.
  2. Save the file.

Run your project and sign in

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

    cd 1-Authentication\0-sign-in-vanillajs\App
    npm install
    npm start
    
  2. Copy the https URL that appears in the terminal, for example, https://localhost:3000, and paste it into a browser. We recommend using a private or incognito browser session.

  3. Sign-in with an account registered to the tenant.

  4. The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.

    Screenshot of JavaScript App depicting the results of the API call.

Sign out from the application

  1. Find the Sign out button on the page, and select it.
  2. You'll be prompted to pick an account to sign out from. Select the account you used to sign in.

A message appears indicating that you have signed out. You can now close the browser window.