Share via


Zelfstudie: Verificatiestromen afhandelen in een Angular SPA

Deze zelfstudie is deel 3 van een reeks die laat zien hoe u een Angular-app met één pagina (SPA) bouwt en voorbereidt op verificatie. In deel 2 van deze reeks hebt u een Angular SPA gemaakt en voorbereid op verificatie met uw externe tenant. In deze zelfstudie leert u hoe u verificatiestromen in uw app kunt verwerken door MSAL-onderdelen (Microsoft Authentication Library) toe te voegen.

In deze zelfstudie;

  • Verificatiestromen toevoegen aan uw toepassing
  • MSAL-onderdelen importeren
  • Voeg routes toe aan de startpagina en beveiligde onderdelen van de toepassing.

Vereisten

Maak het verificatieconfiguratiebestand auth-config.ts

  1. Maak een nieuw bestand met de naam auth-config.ts in de map src/app/ en voeg het volgende codefragment toe. Dit bestand bevat verificatieparameters. Deze parameters worden gebruikt voor het initialiseren van Angular- en MSAL Angular-configuraties.

    
    /**
     * 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. Vervang de volgende waarden door de waarden uit het Microsoft Entra-beheercentrum:

    • Zoek de Enter_the_Application_Id_Here waarde en vervang deze door de toepassings-id (clientId) van de app die u hebt geregistreerd in het Microsoft Entra-beheercentrum.
    • Zoek en vervang deze in instantieEnter_the_Tenant_Subdomain_Here door het subdomein van uw tenant. Als uw primaire tenantdomein bijvoorbeeld is contoso.onmicrosoft.com, gebruikt u contoso. Als u uw tenantnaam niet hebt, leest u de details van uw tenant.
  3. Sla het bestand op.

Aangepast URL-domein gebruiken (optioneel)

Gebruik een aangepast domein om de verificatie-URL volledig te merken. Vanuit gebruikersperspectief blijven gebruikers in uw domein tijdens het verificatieproces in plaats van omgeleid naar ciamlogin.com domeinnaam.

Gebruik de volgende stappen om een aangepast domein te gebruiken:

  1. Gebruik de stappen in Aangepaste URL-domeinen inschakelen voor apps in externe tenants om aangepast URL-domein in te schakelen voor uw externe tenant.

  2. Zoek vervolgens in het authConfig.js-bestand naar auth het object en vervolgens:

    1. Werk de waarde van de authority eigenschap bij naar https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_Here. Vervang Enter_the_Custom_Domain_Here door uw aangepaste URL-domein en Enter_the_Tenant_ID_Here door uw tenant-id. Als u uw tenant-id niet hebt, leest u de details van uw tenant.
    2. Voeg knownAuthorities de eigenschap toe met een waarde [Enter_the_Custom_Domain_Here].

Nadat u de wijzigingen hebt aangebracht in uw authConfig.js-bestand, als uw aangepaste URL-domein is login.contoso.com en uw tenant-id aaaabb-0000-cccc-1111-dddd2222eeeee is, moet uw bestand er ongeveer uitzien als het volgende fragment:

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

MSAL-onderdelen importeren

  1. Open src/app/app.module.ts en voeg het volgende codefragment toe.

    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. Open src/app/app-routing.module.ts en vervang de volledige inhoud van het bestand door het volgende fragment. Hiermee worden routes toegevoegd aan de home en guarded onderdelen.

    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 { }
    

Volgende stap