Tutorial: Crear una aplicación de Angular y prepararla para la autenticación
Una vez completado el registro, se puede crear un proyecto de Angular mediante la CLI de Angular (interfaz de la línea de comandos). En este tutorial se muestra cómo crear una aplicación de página única de Angular mediante la CLI de Angular y crear los archivos necesarios para la autenticación y autorización.
En este tutorial:
- Crear un nuevo proyecto de Angular
- Configure las opciones de la aplicación
- Agregar código de autenticación a la aplicación
Prerrequisitos
- Completar los requisitos previos y los pasos del Tutorial: registrar una aplicación.
- Instalar la CLI de Agular
- Instale Node.js.
- Visual Studio Code
Crear un nuevo proyecto de Angular
Para compilar el proyecto de Angular desde cero, siga estos pasos:
Abra una ventana de terminal y ejecute el siguiente comando para crear un nuevo proyecto de Angular:
ng new msal-angular-tutorial --routing=true --style=css --strict=false
El comando crea un nuevo proyecto de Angular denominado
msal-angular-tutorial
con enrutamiento habilitado, CSS para aplicar estilos y el modo strict deshabilitado.Cambie al directorio del proyecto
cd msal-angular-tutorial
Instalar las dependencias de aplicaciones:
npm install @azure/msal-browser @azure/msal-angular bootstrap
El comando
npm install @azure/msal-browser @azure/msal-angular bootstrap
instala el explorador MSAL de Azure, los paquetes de Azure MSAL Angular y Bootstrap.Abra
angular.json
y agregue la ruta CSS de Bootstrap a la matrizstyles
:"styles": [ "src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.min.css" ],
El código agrega el CSS de Bootstrap a la matriz de estilos en el archivo
angular.json
.Generar componentes de Inicio y Perfil:
ng generate component home ng generate component profile
Los comandos generan los componentes Inicio y Perfil en el proyecto de Angular.
Quite los archivos y el código innecesarios del proyecto:
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
Los comandos quitan archivos y código innecesarios del proyecto.
Cambie el nombre
app.routes.ts
aapp-routing.module.ts
mediante Visual Studio Code y actualice todas las referencias deapp.routes.ts
en toda la aplicación.Cambie el nombre
app.config.ts
aapp.module.ts
mediante Visual Studio Code y actualice todas las referencias aapp.config.ts
en toda la aplicación.
Después de completar estos pasos, la estructura del proyecto debe ser similar a la siguiente:
.
├── 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
Configure las opciones de la aplicación
Usaremos los valores registrados durante el registro de la aplicación para configurarla para la autenticación. Siga estos pasos:
Abra el archivo
src/app/app.module.ts
y reemplace el contenido por el código siguiente:// 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 { }
El código configura MSAL para la autenticación de usuarios y la protección de API. Configura la aplicación con
MsalInterceptor
para proteger las solicitudes de API yMsalGuard
para proteger las rutas, al tiempo que define los componentes y servicios clave para la autenticación. Reemplace los siguientes valores por los del Centro de administración de Microsoft Entra.- Reemplace
Enter_the_Application_Id_Here
conApplication (client) ID
desde el registro de la aplicación. - Reemplace
Enter_the_Tenant_Info_Here
conDirectory (tenant) ID
desde el registro de la aplicación.
- Reemplace
Guarde el archivo.
Agregar código de autenticación a la aplicación
Para controlar la autenticación de usuarios y la administración de sesiones mediante MSAL Angular, deberá actualizar src/app/app.component.ts
.
Abra el archivo
src/app/app.component.ts
y reemplace el contenido por el código siguiente:// 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(); } }
El código integra MSAL con Angular para administrar la autenticación de usuario. Escucha los cambios de estado de inicio de sesión, muestra el estado de inicio de sesión, controla los eventos de adquisición de tokens y proporciona métodos para iniciar o cerrar la sesión de los usuarios en función de la configuración de Microsoft Entra.
Guarde el archivo.