Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
Van toepassing op: Workforce-huurders
Externe huurders (meer informatie)
Deze zelfstudie is het eerste deel van een reeks die laat zien hoe u een Angular-toepassing met één pagina (SPA) bouwt, verificatie toevoegt en gebruikersgegevens extraheert met behulp van het Microsoft Identity Platform.
In deze handleiding leert u:
- Een nieuw Angular-project maken
- De instellingen voor de toepassing configureren
- Verificatiecode toevoegen aan de toepassing
Vereisten
- Een personeelstenant. U kunt uw Default Directory- gebruiken of een nieuwe tenant instellen.
- Registreer een nieuwe app in het Microsoft Entra-beheercentrum, geconfigureerd voor alleen accounts in deze organisatorische directory. Raadpleeg Een applicatie registreren voor meer details. Noteer de volgende waarden van de Overview pagina van de applicatie voor later gebruik.
- Applicatie (client) ID
- Directory-id (huurder)
- Voeg de volgende omleidings-URI's toe met behulp van de configuratie van het toepassingsplatform met één pagina . Raadpleeg Hoe u een omleidings-URI in uw applicatie kunt toevoegen voor meer details.
-
Redirect-URI:
http://localhost:4200/
.
-
Redirect-URI:
- Hoekige CLI
- Node.js 18.19 of nieuwere.
- Visual Studio Code of een andere code-editor.
Een nieuw Angular-project maken
In deze sectie maakt u een nieuw Angular-project met behulp van de Angular CLI in Visual Studio Code. Kies het juiste tabblad op basis van uw tenanttype.
Voer de volgende stappen uit om het volledig nieuwe Angular-project te bouwen:
Open een terminalvenster en voer de volgende opdracht uit om een nieuw Angular-project te maken:
ng new msal-angular-tutorial --routing=true --style=css --strict=false
Met de opdracht maakt u een nieuw Angular-project met de naam
msal-angular-tutorial
routering ingeschakeld, CSS voor stijl en strikte modus uitgeschakeld.Wijzig naar de projectmap:
cd msal-angular-tutorial
App-afhankelijkheden installeren:
npm install @azure/msal-browser @azure/msal-angular bootstrap
Met de opdracht
npm install @azure/msal-browser @azure/msal-angular bootstrap
worden de Azure MSAL-browser, Azure MSAL Angular en Bootstrap-pakketten geïnstalleerd.Open
angular.json
en voeg het CSS-pad van Bootstrap toe aan destyles
array:"styles": [ "src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.min.css" ],
De code voegt de Bootstrap CSS toe aan de stijlenmatrix in het
angular.json
bestand.Onderdelen voor thuisgebruik en profiel genereren:
ng generate component home ng generate component profile
Met de opdrachten worden de onderdelen Home en Profile in het Angular-project gegenereerd.
Verwijder overbodige bestanden en code uit het project:
rm src/app/app.component.css rm src/app/app.component.spec.ts rm src/app/home/home.component.css rm src/app/home/home.component.spec.ts rm src/app/profile/profile.component.css rm src/app/profile/profile.component.spec.ts
Met de opdrachten worden overbodige bestanden en code uit het project verwijderd.
Hernoem
app.routes.ts
naarapp-routing.module.ts
met Visual Studio Code en werk alle verwijzingen vanapp.routes.ts
in de hele toepassing bij.Wijzig
app.config.ts
naarapp.module.ts
met Visual Studio Code en werk alle verwijzingen naarapp.config.ts
in de hele toepassing bij.
Nadat u deze stappen hebt voltooid, moet de projectstructuur er als volgt uitzien:
.
├── README.md
├── angular.json
├── package-lock.json
├── package.json
├── src
│ ├── app
│ │ ├── app-routing.module.ts
│ │ ├── app.component.html
│ │ ├── app.component.ts
│ │ ├── app.module.ts
│ │ ├── home
│ │ │ ├── home.component.html
│ │ │ └── home.component.ts
│ │ └── profile
│ │ ├── profile.component.html
│ │ └── profile.component.ts
│ ├── index.html
│ ├── main.ts
│ ├── polyfills.ts
│ └── styles.css
├── tsconfig.app.json
└── tsconfig.json
Toepassingsinstellingen configureren
In deze sectie configureert u de toepassingsinstellingen voor verificatie. We gebruiken de waarden die tijdens de app-registratie zijn vastgelegd om de toepassing voor verificatie te configureren. Kies het juiste tabblad op basis van uw tenanttype.
We gebruiken de waarden die tijdens de app-registratie zijn vastgelegd om de toepassing voor verificatie te configureren. Volg vervolgens deze stappen:
Open het
src/app/app.module.ts
bestand en vervang de inhoud door de volgende code:// Required for Angular multi-browser support import { BrowserModule } from '@angular/platform-browser'; // Required for Angular import { NgModule } from '@angular/core'; // Required modules and components for this application import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ProfileComponent } from './profile/profile.component'; import { HomeComponent } from './home/home.component'; // HTTP modules required by MSAL import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; // Required for MSAL import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser'; import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular'; const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1; export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: { // 'Application (client) ID' of app registration in the Microsoft Entra admin center - this value is a GUID clientId: "Enter_the_Application_Id_Here", // Full directory URL, in the form of https://login.microsoftonline.com/<tenant> authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here", // Must be the same redirectUri as what was provided in your app registration. redirectUri: "http://localhost:4200", }, cache: { cacheLocation: BrowserCacheLocation.LocalStorage, storeAuthStateInCookie: isIE } }); } // MSAL Interceptor is required to request access tokens in order to access the protected resource (Graph) export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration { const protectedResourceMap = new Map<string, Array<string>>(); protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']); return { interactionType: InteractionType.Redirect, protectedResourceMap }; } // MSAL Guard is required to protect routes and require authentication before accessing protected routes export function MSALGuardConfigFactory(): MsalGuardConfiguration { return { interactionType: InteractionType.Redirect, authRequest: { scopes: ['user.read'] } }; } // Create an NgModule that contains the routes and MSAL configurations @NgModule({ declarations: [ AppComponent, HomeComponent, ProfileComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, MsalModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }, { provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory }, { provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory }, { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory }, MsalService, MsalGuard, MsalBroadcastService ], bootstrap: [AppComponent, MsalRedirectComponent] }) export class AppModule { }
Met de code wordt MSAL ingesteld voor gebruikersverificatie en API-beveiliging. De app wordt geconfigureerd met
MsalInterceptor
om API-aanvragen te beveiligen en metMsalGuard
om routes te beschermen, terwijl belangrijke componenten en services voor authenticatie worden gedefinieerd. Vervang de volgende waarden door de waarden uit het Microsoft Entra-beheercentrum.- Vervang
Enter_the_Application_Id_Here
door het elementApplication (client) ID
uit de app-registratie. - Vervang
Enter_the_Tenant_Info_Here
door het elementDirectory (tenant) ID
uit de app-registratie.
- Vervang
Sla het bestand op.
Verificatiecode toevoegen aan de toepassing
In deze sectie voegt u verificatiecode toe aan de toepassing om gebruikersverificatie en sessiebeheer af te handelen. Kies het juiste tabblad op basis van uw tenanttype.
Open
src/app/app.component.ts
het bestand en vervang de inhoud door de volgende code:// Required for Angular import { Component, OnInit, Inject, OnDestroy } from '@angular/core'; // Required for MSAL import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG, MsalGuardConfiguration } from '@azure/msal-angular'; import { EventMessage, EventType, InteractionStatus, RedirectRequest } from '@azure/msal-browser'; // Required for RJXS import { Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit, OnDestroy { title = 'Angular - MSAL Example'; loginDisplay = false; tokenExpiration: string = ''; private readonly _destroying$ = new Subject<void>(); constructor( @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration, private authService: MsalService, private msalBroadcastService: MsalBroadcastService ) { } // On initialization of the page, display the page elements based on the user state ngOnInit(): void { this.msalBroadcastService.inProgress$ .pipe( filter((status: InteractionStatus) => status === InteractionStatus.None), takeUntil(this._destroying$) ) .subscribe(() => { this.setLoginDisplay(); }); // Used for storing and displaying token expiration this.msalBroadcastService.msalSubject$.pipe(filter((msg: EventMessage) => msg.eventType === EventType.ACQUIRE_TOKEN_SUCCESS)).subscribe(msg => { this.tokenExpiration= (msg.payload as any).expiresOn; localStorage.setItem('tokenExpiration', this.tokenExpiration); }); } // If the user is logged in, present the user with a "logged in" experience setLoginDisplay() { this.loginDisplay = this.authService.instance.getAllAccounts().length > 0; } // Log the user in and redirect them if MSAL provides a redirect URI otherwise go to the default URI login() { if (this.msalGuardConfig.authRequest) { this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest } as RedirectRequest); } else { this.authService.loginRedirect(); } } // Log the user out logout() { this.authService.logoutRedirect(); } ngOnDestroy(): void { this._destroying$.next(undefined); this._destroying$.complete(); } }
De code integreert MSAL met Angular om gebruikersverificatie te beheren. Het luistert naar wijzigingen in de aanmeldingsstatus, geeft de aanmeldingsstatus weer, verwerkt tokenovername-gebeurtenissen en biedt methoden om gebruikers in of uit te loggen op basis van De Configuratie van Microsoft Entra.
Sla het bestand op.