MSAL Angular başlatılıyor

@azure/msal-angular kullanmadan önce, clientId almak için uygulamanızı Microsoft Entra ID’ye kaydedin.

Uygulama modülünüze MSAL modülünü ekleme ve başlatma

MsalModule öğesini app.module.ts dosyasına içeri aktar. MSAL modülünü başlatmak için, uygulama kaydından edindiğiniz uygulamanızın clientId değerini geçirin.

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { MsalModule, MsalService, MsalGuard, MsalInterceptor, MsalBroadcastService, MsalRedirectComponent } from "@azure/msal-angular";
import { PublicClientApplication, InteractionType, BrowserCacheLocation } from "@azure/msal-browser";

@NgModule({
    imports: [
        MsalModule.forRoot( new PublicClientApplication({ // MSAL Configuration
            auth: {
                clientId: "Your client ID",
                authority: "Your authority",
                redirectUri: "Your redirect Uri",
            },
            cache: {
                cacheLocation : BrowserCacheLocation.LocalStorage,
            },
            system: {
                loggerOptions: {
                    loggerCallback: () => {},
                    piiLoggingEnabled: false
                }
            }
        }), {
            interactionType: InteractionType.Redirect, // MSAL Guard Configuration
        }, {
            interactionType: InteractionType.Redirect, // MSAL Interceptor Configuration
        })
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MsalInterceptor,
            multi: true
        },
        MsalService,
        MsalGuard,
        MsalBroadcastService
    ],
    bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule {}

Uygulamanızdaki yolların güvenliğini sağlama

Uygulamanızdaki belirli rotaları güvence altına almak için, rota tanımınıza canActivate: [MsalGuard] ekleyerek kimlik doğrulaması ekleyin. Bunu üst veya alt rotalara ekleyin. Bir kullanıcı bu yolları ziyaret ettiğinde, kitaplık kullanıcıdan kimlik doğrulamasını ister.

Ek arabirimler kullanma dahil olmak üzere yapılandırma ve önemli noktalar hakkında belgemizdeMsalGuard daha fazla bilgi edinin.

aşağıda ile tanımlanan bir yol örneği verilmiştir MsalGuard:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { MsalGuard } from '@azure/msal-angular';

const routes: Routes = [
    {
        path: 'profile',
        component: ProfileComponent,
        canActivate: [MsalGuard]
    },
    {
        path: '',
        component: HomeComponent
    },
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Web API çağrıları için belirteçleri alma

@azure/msal-angular, app.module.ts içinde aşağıdaki gibi bir HTTP yakalayıcısı (MsalInterceptor) eklemenize olanak tanır. MsalInterceptor, protectedResourceMap temelinde belirteçleri alır ve bunları API çağrılarındaki tüm HTTP isteklerinize ekler. Yapılandırma ve kullanım hakkında daha fazla bilgi için MsalInterceptor belgemize bakın.

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { MsalModule, MsalService, MsalGuard, MsalInterceptor, MsalBroadcastService, MsalRedirectComponent } from "@azure/msal-angular";
import { PublicClientApplication, InteractionType, BrowserCacheLocation } from "@azure/msal-browser";

@NgModule({
    imports: [
        MsalModule.forRoot( new PublicClientApplication({ // MSAL Configuration
            auth: {
                clientId: "Your client ID",
                authority: "Your authority",
                redirectUri: "Your redirect Uri",
            },
            cache: {
                cacheLocation : BrowserCacheLocation.LocalStorage,
            },
            system: {
                loggerOptions: {
                    loggerCallback: () => {},
                    piiLoggingEnabled: false
                }
            }
        }), {
            interactionType: InteractionType.Redirect, // MSAL Guard Configuration
        }, {
            interactionType: InteractionType.Redirect, // MSAL Interceptor Configuration
            protectedResourceMap: new Map([
                ['https://graph.microsoft.com/v1.0/me', ['user.read']],
                ['https://api.myapplication.com/users/*', ['customscope.read']],
                ['http://localhost:4200/about/', null] 
            ])
        })
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MsalInterceptor,
            multi: true
        },
        MsalService,
        MsalGuard,
        MsalBroadcastService
    ],
    bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule {}

MsalInterceptor kullanımı isteğe bağlıdır. Bunun yerine acquireToken API'lerini kullanarak belirteçleri açıkça almak isteyebilirsiniz.

MsalInterceptor öğesinin kullanım kolaylığı sağlamak için sunulduğunu ve tüm kullanım senaryolarına uymayabileceğini unutmayın. MsalInterceptor tarafından karşılanmayan belirli ihtiyaçlarınız varsa kendi ara katmanınızı yazın.

Olaylara Abone Olma

MSAL, kimlik doğrulaması ve MSAL ile ilgili olayları yayan bir olay sistemi sağlar. Olayları kullanmak için bileşeninizdeki veya hizmetinizdeki oluşturucuya MsalBroadcastService öğesini ekleyin.

1. Olaylara abone olma

import { EventMessage, EventType } from '@azure/msal-browser';
import { filter } from 'rxjs/operators';

this.msalBroadcastService.msalSubject$
    .pipe(
        filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS)
    )
    .subscribe((result) => {
        // do something here
    });

2. Mevcut olaylar

MSAL tarafından kullanılabilen olayların listesini olay belgelerinde@azure/msal-browser bulabilirsiniz.

3. Abonelikten çıkılma

Abonelikten çıkmak önemlidir. Aboneliği kaldırmak için bileşeninizde uygulayın ngOnDestroy() .

import { EventMessage, EventType } from '@azure/msal-browser';
import { filter, Subject, takeUntil } from 'rxjs';

private readonly _destroying$ = new Subject<void>();

this.msalBroadcastService.msalSubject$
    .pipe(
        filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
        takeUntil(this._destroying$)
    )
    .subscribe((result) => {
        this.checkAccount();
    });

ngOnDestroy(): void {
    this._destroying$.next(null);
    this._destroying$.complete();
}

Sonraki Adımlar

@azure/msal-angular kullanmaya hazırsınız.