Freigeben über


Tutorial: Verarbeiten von Authentifizierungsflows in einer Angular-SPA

Dieses Tutorial ist Teil 3 einer Reihe, in der das Erstellen einer Single-Page-Webanwendung (SPA) in Angular und ihre Vorbereitung für die Authentifizierung veranschaulicht wird. In Teil 2 dieser Reihe haben Sie eine Angular SPA erstellt und für die Authentifizierung mit Ihrem externen Mandanten vorbereitet. In diesem Tutorial erfahren Sie, wie Sie Authentifizierungsflows in Ihrer App verarbeiten, indem Sie ihr Komponenten der Microsoft-Authentifizierungsbibliothek (Microsoft Authentication Library, MSAL) hinzufügen.

In diesem Tutorial:

  • Hinzufügen von Authentifizierungsflows zu Ihrer Anwendung
  • Importieren von MSAL-Komponenten
  • Fügen Sie Routen zur Startseite und zu geschützten Komponenten der Anwendung hinzu.

Voraussetzungen

Erstellen Sie die Authentifizierungskonfigurationsdatei authConfig.js.

  1. Erstellen Sie eine neue Datei mit dem Namen auth-config.ts im Ordner src/app/, und fügen Sie den folgenden Codeschnipsel hinzu. Diese Datei enthält Authentifizierungsparameter. Diese Parameter werden verwendet, um Angular- und MSAL Angular-Konfigurationen zu initialisieren.

    
    /**
     * This file contains authentication parameters. Contents of this file
     * is roughly the same across other MSAL.js libraries. These parameters
     * are used to initialize Angular and MSAL Angular configurations in
     * in app.module.ts file.
     */
    
    import {
      LogLevel,
      Configuration,
      BrowserCacheLocation,
    } 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: Configuration = {
      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 by default. You must register this URI on Azure portal/App Registration.
        postLogoutRedirectUri: '/', // Points to window.location.origin by default.
      },
      cache: {
        cacheLocation: BrowserCacheLocation.LocalStorage, // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
      },
      system: {
        loggerOptions: {
          loggerCallback(logLevel: LogLevel, message: string) {
            console.log(message);
          },
          logLevel: LogLevel.Verbose,
          piiLoggingEnabled: false,
        },
      },
    };
    
    /**
     * 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/entra/identity-platform/permissions-consent-overview#openid-connect-scopes
     */
    export const loginRequest = {
      scopes: [],
    };
    
  2. Ersetzen Sie die folgenden Werte durch die Werte aus dem Microsoft Entra Admin Center.

    • Suchen Sie den Wert Enter_the_Application_Id_Here und ersetzen Sie ihn durch die Anwendungs-ID (clientId) der App, die Sie im Microsoft Entra Admin Center registriert haben.
    • Suchen Sie in Autorität nach Enter_the_Tenant_Subdomain_Here, und ersetzen Sie es durch die Unterdomäne Ihres Mandanten. Wenn Ihre primäre Mandantendomäne beispielsweise contoso.onmicrosoft.com lautet, verwenden Sie contoso. Wenn Sie Ihren Mandantennamen nicht kennen, erfahren Sie hier, wie Sie Ihre Mandantendetails auslesen.
  3. Speichern Sie die Datei .

Verwenden einer benutzerdefinierten URL-Domäne (Optional)

Verwenden Sie eine benutzerdefinierte Domäne, um die Authentifizierungs-URL vollständig für Ihre Marke anzupassen. Aus Sicht der Benutzer entsteht dadurch der Eindruck, dass sie während des Authentifizierungsprozesses in Ihrer Domäne bleiben, anstatt zum Domänennamen ciamlogin.com umgeleitet zu werden.

Führen Sie die folgenden Schritte aus, um eine benutzerdefinierte Domäne zu verwenden:

  1. Führen Sie die Schritte unter Aktivieren von benutzerdefinierten URL-Domänen für Apps in externen Mandanten aus, um eine benutzerdefinierte URL-Domäne für Ihren externen Mandanten zu aktivieren.

  2. Suchen Sie in Ihrer Datei authConfig.js nach dem auth-Objekt, und führen Sie dann die folgenden Schritte aus:

    1. Aktualisieren Sie den Wert der authority-Eigenschaft in https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_Here. Ersetzen Sie Enter_the_Custom_Domain_Here durch die benutzerdefinierte URL-Domäne und Enter_the_Tenant_ID_Here durch Ihre Mandanten-ID. Wenn Sie Ihre Mandanten-ID nicht kennen, erfahren Sie hier, wie Sie die Mandantendetails abrufen.
    2. Fügen Sie die knownAuthorities-Eigenschaft mit dem Wert [Enter_the_Custom_Domain_Here] hinzu.

Nachdem Sie die Änderungen an der Datei authConfig.js vorgenommen haben, sollte die Datei in etwa wie der folgende Codeschnipsel aussehen (wenn Ihre benutzerdefinierte URL-Domäne login.contoso.com lautet und Ihre Mandanten-ID aaaabbbb-0000-cccc-1111-dddd2222eeee ist):

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

Importieren von MSAL-Komponenten

  1. Öffnen Sie src/app/app.module.ts, und fügen Sie den folgenden Codeschnipsel hinzu.

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
    
    import { MatToolbarModule } from "@angular/material/toolbar";
    import { MatButtonModule } from '@angular/material/button';
    import { MatCardModule } from '@angular/material/card';
    import { MatTableModule } from '@angular/material/table';
    import { MatMenuModule } from '@angular/material/menu';
    import { MatDialogModule } from '@angular/material/dialog';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { MatIconModule } from '@angular/material/icon';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { HomeComponent } from './home/home.component';
    import { GuardedComponent } from './guarded/guarded.component';
    
    import {
        IPublicClientApplication,
        PublicClientApplication,
        InteractionType,
    } from '@azure/msal-browser';
    
    import {
        MSAL_INSTANCE,
        MsalGuardConfiguration,
        MSAL_GUARD_CONFIG,
        MsalService,
        MsalBroadcastService,
        MsalGuard,
        MsalRedirectComponent,
        MsalInterceptor,
        MsalModule,
    } from '@azure/msal-angular';
    
    import { msalConfig, loginRequest } from './auth-config';
    
    /**
     * Here we pass the configuration parameters to create an MSAL instance.
        * For more info, visit: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/configuration.md
        */
    export function MSALInstanceFactory(): IPublicClientApplication {
        return new PublicClientApplication(msalConfig);
    }
    
    /**
     * Set your default interaction type for MSALGuard here. If you have any
        * additional scopes you want the user to consent upon login, add them here as well.
        */
    export function MsalGuardConfigurationFactory(): MsalGuardConfiguration {
        return {
        interactionType: InteractionType.Redirect,
        authRequest: loginRequest
        };
    }
    
    @NgModule({
        declarations: [
        AppComponent,
        HomeComponent,
        GuardedComponent,
        ],
        imports: [
        BrowserModule,
        BrowserAnimationsModule,
        AppRoutingModule,
        MatToolbarModule,
        MatButtonModule,
        MatCardModule,
        MatTableModule,
        MatMenuModule,
        HttpClientModule,
        BrowserAnimationsModule,
        MatDialogModule,
        MatIconModule,
        MsalModule,
        ],
        providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MsalInterceptor,
            multi: true,
        },
        {
            provide: MSAL_INSTANCE,
            useFactory: MSALInstanceFactory,
        },
        {
            provide: MSAL_GUARD_CONFIG,
            useFactory: MsalGuardConfigurationFactory,
        },
        MsalService,
        MsalBroadcastService,
        MsalGuard,
        ],
        bootstrap: [AppComponent, MsalRedirectComponent],
    })
    export class AppModule { }
    
  2. Öffnen Sie src/app/app-routing.module.ts, und ersetzen Sie den kompletten Dateiinhalt durch den folgenden Codeschnipsel. Dadurch werden Routen zu den Komponenten home und guarded hinzugefügt.

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { BrowserUtils } from '@azure/msal-browser';
    import { MsalGuard } from '@azure/msal-angular';
    
    import { HomeComponent } from './home/home.component';
    import { GuardedComponent } from './guarded/guarded.component';
    
    /**
     * MSAL Angular can protect routes in your application
        * using MsalGuard. For more info, visit:
        * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/initialization.md#secure-the-routes-in-your-application
        */
    const routes: Routes = [
        {
        path: 'guarded',
        component: GuardedComponent,
        canActivate: [
            MsalGuard
        ]
        },
        {
        path: '',
        component: HomeComponent,
        },
    ];
    
    @NgModule({
        imports: [
        RouterModule.forRoot(routes, {
            // Don't perform initial navigation in iframes or popups
            initialNavigation:
            !BrowserUtils.isInIframe() && !BrowserUtils.isInPopup()
                ? 'enabledNonBlocking'
                : 'disabled', // Set to enabledBlocking to use Angular Universal
        }),
        ],
        exports: [RouterModule],
    })
    export class AppRoutingModule { }
    

Nächster Schritt