Condividi tramite


Esercitazione: Gestire flussi di autenticazione in un'applicazione a pagina singola JavaScript Vanilla

Questa esercitazione è la terza parte di una serie che illustra la creazione di un'applicazione a pagina singola (SPA) Vanilla JavaScript (JS) e la preparazione per l'autenticazione. Nella Parte 2 di questa serie è stata creata un'applicazione a pagina singola (SPA) Vanilla JS che quindi è stata preparata per l'autenticazione con tenant esterno. In questa esercitazione viene descritto come gestire i flussi di autenticazione nell'app aggiungendo i componenti di Microsoft Authentication Library (MSAL).

Contenuto dell'esercitazione:

  • Configurare le impostazioni per l'applicazione
  • Aggiungere codice a authRedirect.js per gestire il flusso di autenticazione
  • Aggiungere codice a authPopup.js per gestire il flusso di autenticazione

Prerequisiti

Modificare il file di configurazione dell'autenticazione

  1. Aprire public/authConfig.js e aggiungere il frammento di codice seguente:

    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', // This is the ONLY mandatory field that you need to supply.
            authority: 'https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/', // Replace the placeholder with your tenant subdomain 
            redirectUri: '/', // Points to window.location.origin. You must register this URI on Azure Portal/App Registration.
            postLogoutRedirectUri: '/', // Indicates the page to navigate after logout.
            navigateToLoginRequestUrl: false, // 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 between tabs.
            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: [],
    };
    
  2. Sostituire i valori seguenti con i valori dal portale di Azure:

    • Trovare il valore Enter_the_Application_Id_Here e sostituirlo con l'ID applicazione (clientId) dell'app registrata nell'Interfaccia di amministrazione di Microsoft Entra.
      • In Autorità, trovare Enter_the_Tenant_Subdomain_Here e sostituirlo con il sottodominio del tenant. Ad esempio, se il dominio primario del tenant è contoso.onmicrosoft.com, usare contoso. Se non si dispone del nome del tenant, vedere informazioni su come leggere i dettagli del tenant.
  3. Salvare il file.

Usare un dominio URL personalizzato (facoltativo)

Usare un dominio personalizzato per personalizzare completamente l'URL di autenticazione. Dal punto di vista dell'utente, gli utenti rimangono nel dominio durante il processo di autenticazione, anziché essere reindirizzati a ciamlogin.com nome di dominio.

Usare la procedura seguente per utilizzare un dominio personalizzato:

  1. Usare la procedura descritta in Abilitare domini URL personalizzati per le app nei tenant esterni per abilitare il dominio URL personalizzato per il tenant esterno.

  2. Nel file authConfig.js individuare l'oggetto auth e quindi:

    1. Aggiornare il valore della proprietà da authority a https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_Here. Sostituire Enter_the_Custom_Domain_Here con il dominio URL personalizzato e Enter_the_Tenant_ID_Here con l'ID tenant. Se non si ha l’ID del tenant, vedere come leggere i dettagli del tenant.
    2. Aggiungere una proprietà knownAuthorities con un valore [Enter_the_Custom_Domain_Here].

Dopo aver apportato le modifiche al file authConfig.js, se il dominio URL personalizzato è login.contoso.com e l'ID tenant è aaaabbbbbb-0000-cccc-1111-dddd2222eee, allora il file sarà simile al frammento di codice seguente:

//...
const msalConfig = {
    auth: {
        authority: process.env.AUTHORITY || 'https://login.contoso.com/aaaabbbb-0000-cccc-1111-dddd2222eeee', 
        knownAuthorities: ["login.contoso.com"],
        //Other properties
    },
    //...
};

Aggiunta di codice al file di reindirizzamento

Per gestire la risposta dalla pagina di accesso, è necessario un file di reindirizzamento. Viene usato per estrarre il token di accesso dal frammento di URL e usarlo per chiamare l'API protetta. Viene usato anche per gestire gli errori che si verificano durante il processo di autenticazione.

  1. Aprire public/authRedirect.js e aggiungere il frammento di codice seguente:

    // Create the main myMSALObj instance
    // configuration parameters are located at authConfig.js
    const myMSALObj = new msal.PublicClientApplication(msalConfig);
    
    let username = "";
    
    /**
    * A promise handler needs to be registered for handling the
    * response returned from redirect flow. For more information, visit:
    * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/initialization.md#redirect-apis
    */
    myMSALObj.handleRedirectPromise()
        .then(handleResponse)
        .catch((error) => {
            console.error(error);
        });
    
    function selectAccount() {
    
        /**
        * See here for more info on account retrieval: 
        * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
        */
    
        const currentAccounts = myMSALObj.getAllAccounts();
    
        if (!currentAccounts) {
            return;
        } else if (currentAccounts.length > 1) {
            // Add your account choosing logic here
            console.warn("Multiple accounts detected.");
        } else if (currentAccounts.length === 1) {
            username = currentAccounts[0].username
            welcomeUser(currentAccounts[0].username);
            updateTable(currentAccounts[0]);
        }
    }
    
    function handleResponse(response) {
    
        /**
        * To see the full list of response object properties, visit:
        * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#response
        */
    
        if (response !== null) {
            username = response.account.username
            welcomeUser(username);
            updateTable(response.account);
        } else {
            selectAccount();
    
        }
    }
    
    function signIn() {
    
        /**
        * You can pass a custom request object below. This will override the initial configuration. For more information, visit:
        * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
        */
    
        myMSALObj.loginRedirect(loginRequest);
    }
    
    function signOut() {
    
        /**
        * You can pass a custom request object below. This will override the initial configuration. For more information, visit:
        * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
        */
    
        // Choose which account to logout from by passing a username.
        const logoutRequest = {
            account: myMSALObj.getAccountByUsername(username),
            postLogoutRedirectUri: '/signout', // remove this line if you would like navigate to index page after logout.
    
        };
    
        myMSALObj.logoutRedirect(logoutRequest);
    }
    
  2. Salvare il file.

Aggiunta di codice al file authPopup.js

L'applicazione usa authPopup.js per gestire il flusso di autenticazione quando l'utente accede usando la finestra popup. La finestra popup viene usata quando l'utente è già connesso e l'applicazione deve ottenere un token di accesso per una risorsa diversa.

  1. Aprire public/authPopup.js e aggiungere il frammento di codice seguente:

    // Create the main myMSALObj instance
    // configuration parameters are located at authConfig.js
    const myMSALObj = new msal.PublicClientApplication(msalConfig);
    
    let username = "";
    
    function selectAccount () {
    
        /**
         * See here for more info on account retrieval: 
         * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
         */
    
        const currentAccounts = myMSALObj.getAllAccounts();
    
        if (!currentAccounts  || currentAccounts.length < 1) {
            return;
        } else if (currentAccounts.length > 1) {
            // Add your account choosing logic here
            console.warn("Multiple accounts detected.");
        } else if (currentAccounts.length === 1) {
            username = currentAccounts[0].username
            welcomeUser(currentAccounts[0].username);
            updateTable(currentAccounts[0]);
        }
    }
    
    function handleResponse(response) {
    
        /**
         * To see the full list of response object properties, visit:
         * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#response
         */
    
        if (response !== null) {
            username = response.account.username
            welcomeUser(username);
            updateTable(response.account);
        } else {
            selectAccount();
        }
    }
    
    function signIn() {
    
        /**
         * You can pass a custom request object below. This will override the initial configuration. For more information, visit:
         * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
         */
    
        myMSALObj.loginPopup(loginRequest)
            .then(handleResponse)
            .catch(error => {
                console.error(error);
            });
    }
    
    function signOut() {
    
        /**
         * You can pass a custom request object below. This will override the initial configuration. For more information, visit:
         * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
         */
    
        // Choose which account to logout from by passing a username.
        const logoutRequest = {
            account: myMSALObj.getAccountByUsername(username),
            mainWindowRedirectUri: '/signout'
        };
    
        myMSALObj.logoutPopup(logoutRequest);
    }
    
    selectAccount();
    
  2. Salvare il file.

Passaggio successivo