Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Buradan başlamadan önce uygulama nesnesini nasıl başlatabileceğinizi anladığınızdan emin olun.
@azure/msal-angular tarafından kullanıma sunulan @azure/msal-browserolay sistemini kullanır. Bu sistem kimlik doğrulaması ve MSAL ile ilgili olayları yayar ve kullanıcı arabirimini güncelleştirmek, hata iletilerini göstermek vb. için kullanılabilir.
Uygulamanızda olayları kullanma
@azure/msal-angular içindeki olaylar MsalBroadcastService tarafından yönetilir ve MsalBroadcastService üzerindeki msalSubject$ gözlemlenebilir öğesine abone olarak erişilebilir.
Burada, uygulamanızda yayılan olayları nasıl kullanabileceğinize ilişkin bir örnek verilmiştir:
import { MsalBroadcastService } from '@azure/msal-angular';
import { EventMessage, EventType } from '@azure/msal-browser';
export class AppComponent implements OnInit, OnDestroy {
private readonly _destroying$ = new Subject<void>();
constructor(
//...
private msalBroadcastService: MsalBroadcastService
) {}
ngOnInit(): void {
this.msalBroadcastService.msalSubject$
.pipe(
// Optional filtering of events.
filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
takeUntil(this._destroying$)
)
.subscribe((result: EventMessage) => {
// Do something with the result
});
}
ngOnDestroy(): void {
this._destroying$.next(null);
this._destroying$.complete();
}
}
Derleme hatalarını önlemek için result.payload öğesini belirli bir türe dönüştürmeniz gerekebileceğini unutmayın. Yük türü olaya bağlıdır ve buradaki belgelerimizde bulunabilir.
ngOnInit(): void {
this.msalBroadcastService.msalSubject$
.pipe(
filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
)
.subscribe((result: EventMessage) => {
// Casting payload as AuthenticationResult to access account
const payload = result.payload as AuthenticationResult;
this.authService.instance.setActiveAccount(payload.account);
});
}
Olayları kullanmanın tam örneği için lütfen buradaki örneğimize bakın.
Olaylar tablosu
EventMessage nesnesi hakkında daha fazla bilgi edinmek ve şu anda @azure/msal-browser tarafından yayımlanan olayların tam tablosunu (açıklamalar ve ilgili veri yükleri dahil) görmek için lütfen buradaki belgelere göz atın.
Olaylarla ilgili hataları işleme
EventError içinde EventMessage olarak tanımlandığı gibiAuthError | Error | null, belirli özelliklere erişmeden önce bir hatanın doğru tür olarak doğrulanması gerekir.
TypeScript hatalarını önlemek için bir hatanın AuthError türüne nasıl dönüştürülebileceğine ilişkin aşağıdaki örneğe bakın:
import { MsalBroadcastService } from '@azure/msal-angular';
import { EventMessage, EventType } from '@azure/msal-browser';
export class AppComponent implements OnInit, OnDestroy {
private readonly _destroying$ = new Subject<void>();
constructor(
//...
private msalBroadcastService: MsalBroadcastService
) {}
ngOnInit(): void {
this.msalBroadcastService.msalSubject$
.pipe(
// Optional filtering of events
filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_FAILURE),
takeUntil(this._destroying$)
)
.subscribe((result: EventMessage) => {
if (result.error instanceof AuthError) {
// Do something with the error
}
});
}
ngOnDestroy(): void {
this._destroying$.next(null);
this._destroying$.complete();
}
}
Hata işleme örneği MSAL Angular B2C Örneğimizde de bulunabilir.
Sekmeler ve pencereler arasında oturum durumunu senkronize etme
Bir kullanıcı uygulamanızda farklı bir sekmede veya pencerede oturum açtığında ya da oturumu kapattığında kullanıcı arayüzünüzü güncellemek istiyorsanız, ACCOUNT_ADDED ve ACCOUNT_REMOVED olaylarına abone olabilirsiniz. Yük, eklenen veya kaldırılan nesne olacaktır AccountInfo .
import { MsalService, MsalBroadcastService } from '@azure/msal-angular';
import { EventMessage, EventType } from '@azure/msal-browser';
export class AppComponent implements OnInit, OnDestroy {
private readonly _destroying$ = new Subject<void>();
constructor(
//...
private authService: MsalService,
private msalBroadcastService: MsalBroadcastService
) {}
ngOnInit(): void {
this.authService.instance.enableAccountStorageEvents(); // Register the storage listener that will be emitting the events
this.msalBroadcastService.msalSubject$
.pipe(
// Optional filtering of events
filter((msg: EventMessage) => msg.eventType === EventType.ACCOUNT_ADDED || msg.eventType === EventType.ACCOUNT_REMOVED),
takeUntil(this._destroying$)
)
.subscribe((result: EventMessage) => {
if (this.authService.msalInstance.getAllAccounts().length === 0) {
// Account logged out in a different tab, redirect to homepage
window.location.pathname = "/";
} else {
// Update UI to show user is signed in. result.payload contains the account that was logged in
}
});
}
ngOnDestroy(): void {
this._destroying$.next(null);
this._destroying$.complete();
}
}
Örneklerimizde tam bir örnek de bulunabilir.
inProgress$ Observable'ı
inProgress$ gözlemlenebilir, MsalBroadcastService tarafından da işlenir ve uygulamanın etkileşimlerin durumunu bilmesi gerektiğinde, özellikle etkileşimlerin tamamlandığını doğrulamak için buna abone olunmalıdır. Etkileşimlerin durumunun kullanıcı hesaplarını içeren işlevlerden önce olup olmadığını InteractionStatus.None denetlemenizi öneririz.
inProgress$ gözlemlenebilirine abone olunduğunda, son / en güncel InteractionStatus değerinin de mevcut olacağını unutmayın.
Kullanımı için aşağıdaki örniğe bakın. Örneklerimizde tam bir örnek de bulunabilir. Etkileşim durumlarının tam listesi burada bulunabilir.
import { Component, OnInit, Inject, OnDestroy } from '@angular/core';
import { MsalBroadcastService} from '@azure/msal-angular';
import { InteractionStatus } from '@azure/msal-browser';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
private readonly _destroying$ = new Subject<void>();
constructor(
private msalBroadcastService: MsalBroadcastService
) {}
ngOnInit(): void {
this.msalBroadcastService.inProgress$
.pipe(
// Filtering for all interactions to be completed
filter((status: InteractionStatus) => status === InteractionStatus.None),
takeUntil(this._destroying$)
)
.subscribe(() => {
// Do something related to user accounts or UI here
})
}
ngOnDestroy(): void {
this._destroying$.next(null);
this._destroying$.complete();
}
}
İsteğe Bağlı MsalBroadcastService Yapılandırmalar
MsalBroadcastService isteğe bağlı olarak, abone olunduğunda geçmiş olayları yeniden oynatacak şekilde yapılandırılabilir. Varsayılan olarak, MsalBroadcastService'a abone olunduktan sonra yayınlanan olaylar kullanılabilir. Abonelik öncesi olayların gerekli olduğu örnekler olabilir.
MsalBroadcastService için bir yapılandırma sağlayıp eventsToReplay parametresini bir sayıya ayarlayarak, abone olunduğunda bu sayıda geçmiş olay kullanılabilir olur.
Olayları yeniden yürütme hakkında daha fazla bilgi için buradaki ReplaySubjects ile ilgili RxJS belgelerine bakın.
MsalBroadcastService app.module.ts dosyasında aşağıdaki gibi yapılandırılabilir:
// app.module.ts
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { MsalModule, MsalService, MsalGuard, MsalInterceptor, MsalBroadcastService, MsalRedirectComponent, MSAL_BROADCAST_CONFIG } from "@azure/msal-angular"; // Import MsalBroadcastService and MSAL_BROADCAST_CONFIG here
import { PublicClientApplication, InteractionType, BrowserCacheLocation } from "@azure/msal-browser";
@NgModule({
imports: [
MsalModule.forRoot( new PublicClientApplication({ // MSAL Configuration
auth: {
clientId: "clientid",
authority: "https://login.microsoftonline.com/common/",
redirectUri: "http://localhost:4200/",
postLogoutRedirectUri: "http://localhost:4200/",
navigateToLoginRequestUrl: true
},
cache: {
cacheLocation : BrowserCacheLocation.LocalStorage,
},
system: {
loggerOptions: {
loggerCallback: () => {},
piiLoggingEnabled: false
}
}
}), {
interactionType: InteractionType.Popup, // MSAL Guard Configuration
authRequest: {
scopes: ['user.read']
},
loginFailedRoute: "/login-failed"
}, {
interactionType: InteractionType.Redirect, // MSAL Interceptor Configuration
protectedResourceMap
})
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
{
provide: MSAL_BROADCAST_CONFIG, // Add configuration to providers here
useValue: {
eventsToReplay: 2 // Set how many events you want to replay when subscribing
}
},
MsalGuard,
MsalBroadcastService // Ensure the MsalBroadcastService is provided
],
bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule {}