@azure/msal-angular 6.2.2 → 6.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,866 +1,722 @@
1
- import * as i0 from '@angular/core';
2
- import { InjectionToken, Inject, Optional, Injectable, Component, NgModule } from '@angular/core';
3
- import { InteractionStatus, EventMessageUtils, WrapperSKU, InteractionType, BrowserConfigurationAuthError, BrowserUtils, NavigationClient } from '@azure/msal-browser';
4
- import { ReplaySubject, Subject, BehaviorSubject, from, of, EMPTY } from 'rxjs';
5
- import * as i3 from '@angular/common';
6
- import { DOCUMENT, CommonModule } from '@angular/common';
7
- import { map, concatMap, catchError, switchMap, take, filter } from 'rxjs/operators';
8
- import * as i4 from '@angular/router';
9
-
10
- /* eslint-disable header/header */
1
+ import * as i0 from "@angular/core";
2
+ import { Component, Inject, Injectable, InjectionToken, NgModule, Optional } from "@angular/core";
3
+ import { BrowserConfigurationAuthError, BrowserUtils, EventMessageUtils, InteractionStatus, InteractionType, NavigationClient, WrapperSKU } from "@azure/msal-browser";
4
+ import { BehaviorSubject, EMPTY, ReplaySubject, Subject, from, of } from "rxjs";
5
+ import * as i1 from "@angular/common";
6
+ import { CommonModule, DOCUMENT } from "@angular/common";
7
+ import { catchError, concatMap, filter, map, switchMap, take } from "rxjs/operators";
8
+ import * as i4 from "@angular/router";
11
9
  const name = "@azure/msal-angular";
12
- const version = "6.2.2";
13
-
14
- /*
15
- * Copyright (c) Microsoft Corporation. All rights reserved.
16
- * Licensed under the MIT License.
17
- */
10
+ const version = "6.2.3";
18
11
  const MSAL_INSTANCE = new InjectionToken("MSAL_INSTANCE");
19
12
  const MSAL_GUARD_CONFIG = new InjectionToken("MSAL_GUARD_CONFIG");
20
13
  const MSAL_INTERCEPTOR_CONFIG = new InjectionToken("MSAL_INTERCEPTOR_CONFIG");
21
14
  const MSAL_BROADCAST_CONFIG = new InjectionToken("MSAL_BROADCAST_CONFIG");
22
-
23
- /*
24
- * Copyright (c) Microsoft Corporation. All rights reserved.
25
- * Licensed under the MIT License.
26
- */
27
- class MsalBroadcastService {
28
- constructor(msalInstance, ngZone, msalBroadcastConfig) {
29
- this.msalInstance = msalInstance;
30
- this.ngZone = ngZone;
31
- this.msalBroadcastConfig = msalBroadcastConfig;
32
- // Make _msalSubject a ReplaySubject if configured to replay past events
33
- if (this.msalBroadcastConfig &&
34
- this.msalBroadcastConfig.eventsToReplay > 0) {
35
- this.msalInstance
36
- .getLogger()
37
- .clone(name, version)
38
- .verbose(`BroadcastService - eventsToReplay set on BroadcastConfig, replaying the last ${this.msalBroadcastConfig.eventsToReplay} events`, "");
39
- this._msalSubject = new ReplaySubject(this.msalBroadcastConfig.eventsToReplay);
40
- }
41
- else {
42
- // Defaults to _msalSubject being a Subject
43
- this._msalSubject = new Subject();
44
- }
45
- this.msalSubject$ = this._msalSubject.asObservable();
46
- // InProgress as BehaviorSubject so most recent inProgress state will be available upon subscription
47
- this._inProgress = new BehaviorSubject(InteractionStatus.Startup);
48
- this.inProgress$ = this._inProgress.asObservable();
49
- this.msalInstance.addEventCallback((message) => {
50
- this.ngZone.run(() => {
51
- this._msalSubject.next(message);
52
- const status = EventMessageUtils.getInteractionStatusFromEvent(message, this._inProgress.value);
53
- if (status !== null) {
54
- this.msalInstance
55
- .getLogger()
56
- .clone(name, version)
57
- .verbose(`BroadcastService - ${message.eventType} results in setting inProgress from ${this._inProgress.value} to ${status}`, "");
58
- this._inProgress.next(status);
59
- }
60
- });
61
- });
62
- }
63
- /**
64
- * Resets inProgress state to None
65
- */
66
- resetInProgressEvent() {
67
- if (this._inProgress.value === InteractionStatus.Startup) {
68
- this._inProgress.next(InteractionStatus.None);
69
- }
70
- }
71
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalBroadcastService, deps: [{ token: MSAL_INSTANCE }, { token: i0.NgZone }, { token: MSAL_BROADCAST_CONFIG, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
72
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalBroadcastService }); }
73
- }
74
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalBroadcastService, decorators: [{
75
- type: Injectable
76
- }], ctorParameters: () => [{ type: undefined, decorators: [{
77
- type: Inject,
78
- args: [MSAL_INSTANCE]
79
- }] }, { type: i0.NgZone }, { type: undefined, decorators: [{
80
- type: Optional
81
- }, {
82
- type: Inject,
83
- args: [MSAL_BROADCAST_CONFIG]
84
- }] }] });
85
-
86
- /*
87
- * Copyright (c) Microsoft Corporation. All rights reserved.
88
- * Licensed under the MIT License.
89
- */
90
- class MsalService {
91
- constructor(instance, location, injector) {
92
- this.instance = instance;
93
- this.location = location;
94
- this.injector = injector;
95
- const hash = this.location.path(true).split("#").pop();
96
- if (hash) {
97
- this.redirectHash = `#${hash}`;
98
- }
99
- this.instance.initializeWrapperLibrary(WrapperSKU.Angular, version);
100
- }
101
- initialize() {
102
- return from(this.instance.initialize());
103
- }
104
- /**
105
- * Ensures the PublicClientApplication has been initialized.
106
- */
107
- withInitialize(call) {
108
- return from(this.instance.initialize().then(() => call()));
109
- }
110
- acquireTokenPopup(request) {
111
- return this.withInitialize(() => this.instance.acquireTokenPopup(request));
112
- }
113
- acquireTokenRedirect(request) {
114
- return this.withInitialize(() => this.instance.acquireTokenRedirect(request));
115
- }
116
- acquireTokenSilent(silentRequest) {
117
- return this.withInitialize(() => this.instance.acquireTokenSilent(silentRequest));
118
- }
119
- handleRedirectObservable(hashOrOptions) {
120
- // Support both legacy string parameter (hash) and new options object
121
- const options = typeof hashOrOptions === "string"
122
- ? { hash: hashOrOptions }
123
- : hashOrOptions || {};
124
- // Only include hash in the final options if there's a value
125
- const hash = options.hash || this.redirectHash;
126
- const finalOptions = {
127
- ...options,
128
- ...(hash ? { hash } : {}),
129
- };
130
- return from(this.instance
131
- .initialize()
132
- .then(() => this.instance.handleRedirectPromise(finalOptions))
133
- .finally(() => {
134
- // update inProgress state to none
135
- this.injector.get(MsalBroadcastService).resetInProgressEvent();
136
- }));
137
- }
138
- loginPopup(request) {
139
- return this.withInitialize(() => this.instance.loginPopup(request));
140
- }
141
- loginRedirect(request) {
142
- return this.withInitialize(() => this.instance.loginRedirect(request));
143
- }
144
- logoutRedirect(logoutRequest) {
145
- return this.withInitialize(() => this.instance.logoutRedirect(logoutRequest));
146
- }
147
- logoutPopup(logoutRequest) {
148
- return this.withInitialize(() => this.instance.logoutPopup(logoutRequest));
149
- }
150
- ssoSilent(request) {
151
- return this.withInitialize(() => this.instance.ssoSilent(request));
152
- }
153
- /**
154
- * Gets logger for msal-angular.
155
- * If no logger set, returns logger instance created with same options as msal-browser
156
- */
157
- getLogger() {
158
- if (!this.logger) {
159
- this.logger = this.instance.getLogger().clone(name, version);
160
- }
161
- return this.logger;
162
- }
163
- // Create a logger instance for msal-angular with the same options as msal-browser
164
- setLogger(logger) {
165
- this.logger = logger.clone(name, version);
166
- this.instance.setLogger(logger);
167
- }
168
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalService, deps: [{ token: MSAL_INSTANCE }, { token: i3.Location }, { token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable }); }
169
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalService }); }
170
- }
171
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalService, decorators: [{
172
- type: Injectable
173
- }], ctorParameters: () => [{ type: undefined, decorators: [{
174
- type: Inject,
175
- args: [MSAL_INSTANCE]
176
- }] }, { type: i3.Location }, { type: i0.Injector }] });
177
-
178
- /*
179
- * Copyright (c) Microsoft Corporation. All rights reserved.
180
- * Licensed under the MIT License.
181
- */
182
- class MsalGuard {
183
- constructor(msalGuardConfig, msalBroadcastService, authService, location, router) {
184
- this.msalGuardConfig = msalGuardConfig;
185
- this.msalBroadcastService = msalBroadcastService;
186
- this.authService = authService;
187
- this.location = location;
188
- this.router = router;
189
- // Subscribing so events in MsalGuard will set inProgress$ observable
190
- this.msalBroadcastService.inProgress$.subscribe();
191
- }
192
- /**
193
- * Parses url string to UrlTree
194
- * @param url
195
- */
196
- parseUrl(url) {
197
- return this.router.parseUrl(url);
198
- }
199
- /**
200
- * Builds the absolute url for the destination page
201
- * @param path Relative path of requested page
202
- * @returns Full destination url
203
- */
204
- getDestinationUrl(path) {
205
- this.authService.getLogger().verbose("Guard - getting destination url", "");
206
- // Absolute base url for the application (default to origin if base element not present)
207
- const baseElements = document.getElementsByTagName("base");
208
- const baseUrl = this.location.normalize(baseElements.length ? baseElements[0].href : window.location.origin);
209
- // Path of page (including hash, if using hash routing)
210
- const pathUrl = this.location.prepareExternalUrl(path);
211
- // Hash location strategy
212
- if (pathUrl.startsWith("#")) {
213
- this.authService
214
- .getLogger()
215
- .verbose("Guard - destination by hash routing", "");
216
- return `${baseUrl}/${pathUrl}`;
217
- }
218
- /*
219
- * If using path location strategy, pathUrl will include the relative portion of the base path (e.g. /base/page).
220
- * Since baseUrl also includes /base, can just concatentate baseUrl + path
221
- */
222
- return `${baseUrl}${path}`;
223
- }
224
- /**
225
- * Interactively prompt the user to login
226
- * @param url Path of the requested page
227
- */
228
- loginInteractively(state) {
229
- const authRequest = typeof this.msalGuardConfig.authRequest === "function"
230
- ? this.msalGuardConfig.authRequest(this.authService, state)
231
- : { ...this.msalGuardConfig.authRequest };
232
- if (this.msalGuardConfig.interactionType === InteractionType.Popup) {
233
- this.authService
234
- .getLogger()
235
- .verbose("Guard - logging in by popup", authRequest.correlationId ?? "");
236
- return this.authService.loginPopup(authRequest).pipe(map((response) => {
237
- this.authService
238
- .getLogger()
239
- .verbose("Guard - login by popup successful, can activate, setting active account", authRequest.correlationId ?? "");
240
- this.authService.instance.setActiveAccount(response.account);
241
- return true;
242
- }));
243
- }
244
- this.authService
245
- .getLogger()
246
- .verbose("Guard - logging in by redirect", authRequest.correlationId ?? "");
247
- const redirectStartPage = this.getDestinationUrl(state.url);
248
- return this.authService
249
- .loginRedirect({
250
- redirectStartPage,
251
- ...authRequest,
252
- })
253
- .pipe(map(() => false));
254
- }
255
- /**
256
- * Helper which checks for the correct interaction type, prevents page with Guard to be set as redirect, and calls handleRedirectObservable
257
- * @param state
258
- */
259
- activateHelper(state) {
260
- if (this.msalGuardConfig.interactionType !== InteractionType.Popup &&
261
- this.msalGuardConfig.interactionType !== InteractionType.Redirect) {
262
- throw new BrowserConfigurationAuthError("invalid_interaction_type", "", "Invalid interaction type provided to MSAL Guard. InteractionType.Popup or InteractionType.Redirect must be provided in the MsalGuardConfiguration");
263
- }
264
- this.authService.getLogger().verbose("MSAL Guard activated", "");
265
- /*
266
- * If a page with MSAL Guard is set as the redirect for acquireTokenSilent,
267
- * short-circuit to prevent redirecting or popups.
268
- */
269
- if (typeof window === "undefined") {
270
- this.authService
271
- .getLogger()
272
- .info("Guard - window is undefined, MSAL does not support server-side token acquisition", "");
273
- return of(true);
274
- }
275
- else {
276
- try {
277
- BrowserUtils.blockReloadInHiddenIframes();
278
- }
279
- catch (error) {
280
- if (!this.authService.instance.getConfiguration().system
281
- .allowRedirectInIframe) {
282
- this.authService
283
- .getLogger()
284
- .warning("Guard - redirectUri set to page with MSAL Guard. It is recommended to not set redirectUri to a page that requires authentication.", "");
285
- return of(false);
286
- }
287
- }
288
- }
289
- /**
290
- * If a loginFailedRoute is set in the config, set this as the loginFailedRoute
291
- */
292
- if (this.msalGuardConfig.loginFailedRoute) {
293
- this.loginFailedRoute = this.parseUrl(this.msalGuardConfig.loginFailedRoute);
294
- }
295
- // Capture current path before it gets changed by handleRedirectObservable
296
- const currentPath = this.location.path(true);
297
- return this.authService.initialize().pipe(concatMap(() => {
298
- return this.authService.handleRedirectObservable();
299
- }), concatMap(() => {
300
- if (!this.authService.instance.getAllAccounts().length) {
301
- if (state) {
302
- this.authService
303
- .getLogger()
304
- .verbose("Guard - no accounts retrieved, log in required to activate", "");
305
- return this.loginInteractively(state);
306
- }
307
- this.authService
308
- .getLogger()
309
- .verbose("Guard - no accounts retrieved, no state, cannot load", "");
310
- return of(false);
311
- }
312
- this.authService
313
- .getLogger()
314
- .verbose("Guard - at least 1 account exists, can activate or load", "");
315
- // Prevent navigating the app to /#code= or /code=
316
- if (state) {
317
- /*
318
- * Path routing:
319
- * state.url: /#code=...
320
- * state.root.fragment: code=...
321
- */
322
- /*
323
- * Hash routing:
324
- * state.url: /code
325
- * state.root.fragment: null
326
- */
327
- const urlContainsCode = this.includesCode(state.url);
328
- const fragmentContainsCode = !!state.root &&
329
- !!state.root.fragment &&
330
- this.includesCode(`#${state.root.fragment}`);
331
- const hashRouting = this.location.prepareExternalUrl(state.url).indexOf("#") === 0;
332
- // Ensure code parameter is in fragment (and not in query parameter), or that hash hash routing is used
333
- if (urlContainsCode && (fragmentContainsCode || hashRouting)) {
334
- this.authService
335
- .getLogger()
336
- .info("Guard - Hash contains known code response, stopping navigation.", "");
337
- // Path routing (navigate to current path without hash)
338
- if (currentPath.indexOf("#") > -1) {
339
- return of(this.parseUrl(this.location.path()));
340
- }
341
- // Hash routing (navigate to root path)
342
- return of(this.parseUrl(""));
343
- }
344
- }
345
- return of(true);
346
- }), catchError((error) => {
347
- this.authService
348
- .getLogger()
349
- .error("Guard - error while logging in, unable to activate", "");
350
- this.authService
351
- .getLogger()
352
- .errorPii(`Guard - error: ${error.message}`, "");
353
- /**
354
- * If a loginFailedRoute is set, checks to see if state is passed before returning route
355
- */
356
- if (this.loginFailedRoute && state) {
357
- this.authService
358
- .getLogger()
359
- .verbose("Guard - loginFailedRoute set, redirecting", "");
360
- return of(this.loginFailedRoute);
361
- }
362
- return of(false);
363
- }));
364
- }
365
- includesCode(path) {
366
- return ((path.lastIndexOf("/code") > -1 &&
367
- path.lastIndexOf("/code") === path.length - "/code".length) || // path.endsWith("/code")
368
- path.indexOf("#code=") > -1 ||
369
- path.indexOf("&code=") > -1);
370
- }
371
- canActivate(route, state) {
372
- this.authService.getLogger().verbose("Guard - canActivate", "");
373
- return this.activateHelper(state);
374
- }
375
- canActivateChild(route, state) {
376
- this.authService.getLogger().verbose("Guard - canActivateChild", "");
377
- return this.activateHelper(state);
378
- }
379
- canMatch() {
380
- this.authService.getLogger().verbose("Guard - canLoad", "");
381
- return this.activateHelper();
382
- }
383
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalGuard, deps: [{ token: MSAL_GUARD_CONFIG }, { token: MsalBroadcastService }, { token: MsalService }, { token: i3.Location }, { token: i4.Router }], target: i0.ɵɵFactoryTarget.Injectable }); }
384
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalGuard }); }
385
- }
386
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalGuard, decorators: [{
387
- type: Injectable
388
- }], ctorParameters: () => [{ type: undefined, decorators: [{
389
- type: Inject,
390
- args: [MSAL_GUARD_CONFIG]
391
- }] }, { type: MsalBroadcastService }, { type: MsalService }, { type: i3.Location }, { type: i4.Router }] });
392
-
393
- /*
394
- * Copyright (c) Microsoft Corporation. All rights reserved.
395
- * Licensed under the MIT License.
396
- */
397
- class MsalInterceptor {
398
- constructor(msalInterceptorConfig, authService, location, msalBroadcastService, document) {
399
- this.msalInterceptorConfig = msalInterceptorConfig;
400
- this.authService = authService;
401
- this.location = location;
402
- this.msalBroadcastService = msalBroadcastService;
403
- this._document = document;
404
- if (this.msalInterceptorConfig.strictMatching === undefined) {
405
- this.authService
406
- .getLogger()
407
- .warning(`[MSAL] strictMatching is enabled by default. See: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/msal-interceptor.md#strict-matching-strictmatching`, "");
408
- }
409
- }
410
- intercept(req, // eslint-disable-line @typescript-eslint/no-explicit-any
411
- next
412
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
413
- ) {
414
- if (this.msalInterceptorConfig.interactionType !== InteractionType.Popup &&
415
- this.msalInterceptorConfig.interactionType !== InteractionType.Redirect) {
416
- throw new BrowserConfigurationAuthError("invalid_interaction_type", "", "Invalid interaction type provided to MSAL Interceptor. InteractionType.Popup, InteractionType.Redirect must be provided in the msalInterceptorConfiguration");
417
- }
418
- this.authService.getLogger().verbose("MSAL Interceptor activated", "");
419
- const scopes = this.getScopesForEndpoint(req.url, req.method);
420
- // If no scopes for endpoint, does not acquire token
421
- if (!scopes || scopes.length === 0) {
422
- this.authService
423
- .getLogger()
424
- .verbose("Interceptor - no scopes for endpoint", "");
425
- return next.handle(req);
426
- }
427
- // Sets account as active account or first account
428
- let account;
429
- const activeAccount = this.authService.instance.getActiveAccount();
430
- if (activeAccount) {
431
- this.authService
432
- .getLogger()
433
- .verbose("Interceptor - active account selected", "");
434
- account = activeAccount;
435
- }
436
- else {
437
- this.authService
438
- .getLogger()
439
- .verbose("Interceptor - no active account, fallback to first account", "");
440
- account = this.authService.instance.getAllAccounts()[0];
441
- }
442
- const authRequest = typeof this.msalInterceptorConfig.authRequest === "function"
443
- ? this.msalInterceptorConfig.authRequest(this.authService, req, {
444
- account: account,
445
- })
446
- : { ...this.msalInterceptorConfig.authRequest, account };
447
- this.authService
448
- .getLogger()
449
- .info(`Interceptor - ${scopes.length} scopes found for endpoint`, "");
450
- this.authService
451
- .getLogger()
452
- .infoPii(`Interceptor - [${scopes}] scopes found for ${req.url}`, "");
453
- return this.acquireToken(authRequest, scopes, account).pipe(switchMap((result) => {
454
- this.authService
455
- .getLogger()
456
- .verbose("Interceptor - setting authorization headers", "");
457
- const headers = req.headers.set("Authorization", `Bearer ${result.accessToken}`);
458
- const requestClone = req.clone({ headers });
459
- return next.handle(requestClone);
460
- }));
461
- }
462
- /**
463
- * Try to acquire token silently. Invoke interaction if acquireTokenSilent rejected with error or resolved with null access token
464
- * @param authRequest Request
465
- * @param scopes Array of scopes for the request
466
- * @param account Account
467
- * @returns Authentication result
468
- */
469
- acquireToken(authRequest, scopes, account) {
470
- // Note: For MSA accounts, include openid scope when calling acquireTokenSilent to return idToken
471
- return this.authService
472
- .acquireTokenSilent({ ...authRequest, scopes, account })
473
- .pipe(catchError(() => {
474
- this.authService
475
- .getLogger()
476
- .error("Interceptor - acquireTokenSilent rejected with error. Invoking interaction to resolve.", authRequest.correlationId ?? "");
477
- return this.msalBroadcastService.inProgress$.pipe(take(1), switchMap((status) => {
478
- if (status === InteractionStatus.None) {
479
- return this.acquireTokenInteractively(authRequest, scopes);
480
- }
481
- return this.msalBroadcastService.inProgress$.pipe(filter((status) => status === InteractionStatus.None), take(1), switchMap(() => this.acquireToken(authRequest, scopes, account)));
482
- }));
483
- }), switchMap((result) => {
484
- if (!result.accessToken) {
485
- this.authService
486
- .getLogger()
487
- .error("Interceptor - acquireTokenSilent resolved with null access token. Known issue with B2C tenants, invoking interaction to resolve.", authRequest.correlationId ?? "");
488
- return this.msalBroadcastService.inProgress$.pipe(filter((status) => status === InteractionStatus.None), take(1), switchMap(() => this.acquireTokenInteractively(authRequest, scopes)));
489
- }
490
- return of(result);
491
- }));
492
- }
493
- /**
494
- * Invoke interaction for the given set of scopes
495
- * @param authRequest Request
496
- * @param scopes Array of scopes for the request
497
- * @returns Result from the interactive request
498
- */
499
- acquireTokenInteractively(authRequest, scopes) {
500
- if (this.msalInterceptorConfig.interactionType === InteractionType.Popup) {
501
- this.authService
502
- .getLogger()
503
- .verbose("Interceptor - error acquiring token silently, acquiring by popup", authRequest.correlationId ?? "");
504
- return this.authService.acquireTokenPopup({ ...authRequest, scopes });
505
- }
506
- this.authService
507
- .getLogger()
508
- .verbose("Interceptor - error acquiring token silently, acquiring by redirect", authRequest.correlationId ?? "");
509
- const redirectStartPage = window.location.href;
510
- this.authService.acquireTokenRedirect({
511
- ...authRequest,
512
- scopes,
513
- redirectStartPage,
514
- });
515
- return EMPTY;
516
- }
517
- /**
518
- * Looks up the scopes for the given endpoint from the protectedResourceMap
519
- * @param endpoint Url of the request
520
- * @param httpMethod Http method of the request
521
- * @returns Array of scopes, or null if not found
522
- *
523
- */
524
- getScopesForEndpoint(endpoint, httpMethod) {
525
- this.authService
526
- .getLogger()
527
- .verbose("Interceptor - getting scopes for endpoint", "");
528
- // Ensures endpoints and protected resources compared are normalized
529
- const normalizedEndpoint = this.location.normalize(endpoint);
530
- const protectedResourcesArray = Array.from(this.msalInterceptorConfig.protectedResourceMap.keys());
531
- const matchingProtectedResources = this.matchResourcesToEndpoint(protectedResourcesArray, normalizedEndpoint);
532
- if (matchingProtectedResources.length > 0) {
533
- return this.matchScopesToEndpoint(this.msalInterceptorConfig.protectedResourceMap, matchingProtectedResources, httpMethod);
534
- }
535
- return null;
536
- }
537
- /**
538
- * Finds resource endpoints that match request endpoint
539
- * @param protectedResourcesEndpoints
540
- * @param endpoint
541
- * @returns
542
- */
543
- matchResourcesToEndpoint(protectedResourcesEndpoints, endpoint) {
544
- const matchingResources = [];
545
- protectedResourcesEndpoints.forEach((key) => {
546
- const normalizedKey = this.location.normalize(key);
547
- // Get url components
548
- const absoluteKey = this.getAbsoluteUrl(normalizedKey);
549
- const keyComponents = new URL(absoluteKey);
550
- const absoluteEndpoint = this.getAbsoluteUrl(endpoint);
551
- const endpointComponents = new URL(absoluteEndpoint);
552
- if (this.checkUrlComponents(keyComponents, endpointComponents)) {
553
- matchingResources.push(key);
554
- }
555
- });
556
- return matchingResources;
557
- }
558
- /**
559
- * Compares URL segments between key and endpoint
560
- * @param key
561
- * @param endpoint
562
- * @returns
563
- */
564
- checkUrlComponents(keyComponents, endpointComponents) {
565
- // URL properties from https://developer.mozilla.org/en-US/docs/Web/API/URL
566
- const urlProperties = [
567
- "protocol",
568
- "host",
569
- "pathname",
570
- "search",
571
- "hash",
572
- ];
573
- // Maps URL property names to the component identifiers used by matchPatternStrict.
574
- const componentMap = {
575
- protocol: "protocol",
576
- host: "host",
577
- pathname: "path",
578
- search: "search",
579
- hash: "hash",
580
- };
581
- const useStrictMatching = this.msalInterceptorConfig.strictMatching !== false;
582
- for (const property of urlProperties) {
583
- if (keyComponents[property]) {
584
- const decodedInput = decodeURIComponent(keyComponents[property]);
585
- if (useStrictMatching) {
586
- /*
587
- * Strict matching (v5 default): anchored patterns, metacharacters
588
- * are treated as literals, host wildcards do not span dot separators.
589
- */
590
- const component = componentMap[property];
591
- if (!this.matchPatternStrict(decodedInput, endpointComponents[property], component)) {
592
- return false;
593
- }
594
- }
595
- else {
596
- // Legacy matching: preserved for backwards compatibility with v4.
597
- if (!this.matchPattern(decodedInput, endpointComponents[property])) {
598
- return false;
599
- }
600
- }
601
- }
602
- }
603
- return true;
604
- }
605
- /**
606
- * Transforms relative urls to absolute urls
607
- * @param url
608
- * @returns
609
- */
610
- getAbsoluteUrl(url) {
611
- const link = this._document.createElement("a");
612
- link.href = url;
613
- return link.href;
614
- }
615
- /**
616
- * Finds scopes from first matching endpoint with HTTP method that matches request
617
- * @param protectedResourceMap Protected resource map
618
- * @param endpointArray Array of resources that match request endpoint
619
- * @param httpMethod Http method of the request
620
- * @returns
621
- */
622
- matchScopesToEndpoint(protectedResourceMap, endpointArray, httpMethod) {
623
- const allMatchedScopes = [];
624
- // Check each matched endpoint for matching HttpMethod and scopes
625
- endpointArray.forEach((matchedEndpoint) => {
626
- const scopesForEndpoint = [];
627
- const methodAndScopesArray = protectedResourceMap.get(matchedEndpoint);
628
- // Return if resource is unprotected
629
- if (methodAndScopesArray === null) {
630
- allMatchedScopes.push(null);
631
- return;
632
- }
633
- if (methodAndScopesArray === undefined) {
634
- return;
635
- }
636
- methodAndScopesArray.forEach((entry) => {
637
- // Entry is either array of scopes or ProtectedResourceScopes object
638
- if (typeof entry === "string") {
639
- scopesForEndpoint.push(entry);
640
- }
641
- else {
642
- // Ensure methods being compared are normalized
643
- const normalizedRequestMethod = httpMethod.toLowerCase();
644
- const normalizedResourceMethod = entry.httpMethod.toLowerCase();
645
- // Method in protectedResourceMap matches request http method
646
- if (normalizedResourceMethod === normalizedRequestMethod) {
647
- // Validate if scopes comes null to unprotect the resource in a certain http method
648
- if (entry.scopes === null) {
649
- allMatchedScopes.push(null);
650
- }
651
- else {
652
- entry.scopes.forEach((scope) => {
653
- scopesForEndpoint.push(scope);
654
- });
655
- }
656
- }
657
- }
658
- });
659
- // Only add to all scopes if scopes for endpoint and method is found
660
- if (scopesForEndpoint.length > 0) {
661
- allMatchedScopes.push(scopesForEndpoint);
662
- }
663
- });
664
- if (allMatchedScopes.length > 0) {
665
- if (allMatchedScopes.length > 1) {
666
- this.authService
667
- .getLogger()
668
- .warning("Interceptor - More than 1 matching scopes for endpoint found.", "");
669
- }
670
- // Returns scopes for first matching endpoint
671
- return allMatchedScopes[0];
672
- }
673
- return null;
674
- }
675
- /**
676
- * Tests if a given string matches a given pattern, with support for wildcards and queries.
677
- * @param pattern Wildcard pattern to string match. Supports "*" for wildcards and "?" for queries
678
- * @param input String to match against
679
- */
680
- matchPattern(pattern, input) {
681
- /**
682
- * Wildcard support: https://stackoverflow.com/a/3117248/4888559
683
- * Queries: replaces "?" in string with escaped "\?" for regex test
684
- */
685
- // eslint-disable-next-line security/detect-non-literal-regexp
686
- const regex = new RegExp(pattern
687
- .replace(/\\/g, "\\\\")
688
- .replace(/\*/g, "[^ ]*")
689
- .replace(/\?/g, "\\?"));
690
- return regex.test(input);
691
- }
692
- /**
693
- * Tests if a given string matches a given pattern using stricter, anchored
694
- * matching semantics.
695
- *
696
- * Differences from `matchPattern` (legacy):
697
- * - All regex metacharacters (including `.` and `?`) are treated as literals.
698
- * - The generated regex is anchored with `^` and `$` (full-string match).
699
- * - `*` wildcard behaviour depends on the URL component:
700
- * - `host`: `*` maps to `[^.]*` — matches any characters that do NOT
701
- * include `.`, so wildcards stay within a single DNS label.
702
- * - All other components: `*` matches any characters.
703
- *
704
- * @param pattern - The protectedResourceMap key pattern.
705
- * @param input - The URL component value from the outgoing request.
706
- * @param component - Which URL component is being matched.
707
- * @returns `true` if the full input string matches the pattern.
708
- */
709
- matchPatternStrict(pattern, input, component) {
710
- // Step 1: Escape all regex metacharacters so literals (including . and ?) match literally.
711
- let regexBody = pattern.replace(/[.+^${}()|[\]\\*?]/g, "\\$&");
712
- // Step 2: Replace escaped wildcards with component-aware regex equivalents.
713
- if (component === "host") {
714
- regexBody = regexBody.replace(/\\\*/g, "[^.]*");
715
- }
716
- else {
717
- // Path, protocol, search, hash: `*` matches any characters.
718
- regexBody = regexBody.replace(/\\\*/g, ".*");
719
- }
720
- // Step 3: Anchor for full-string matching.
721
- // eslint-disable-next-line security/detect-non-literal-regexp
722
- const regex = new RegExp(`^${regexBody}$`);
723
- return regex.test(input);
724
- }
725
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalInterceptor, deps: [{ token: MSAL_INTERCEPTOR_CONFIG }, { token: MsalService }, { token: i3.Location }, { token: MsalBroadcastService }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable }); }
726
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalInterceptor }); }
727
- }
728
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalInterceptor, decorators: [{
729
- type: Injectable
730
- }], ctorParameters: () => [{ type: undefined, decorators: [{
731
- type: Inject,
732
- args: [MSAL_INTERCEPTOR_CONFIG]
733
- }] }, { type: MsalService }, { type: i3.Location }, { type: MsalBroadcastService }, { type: Document, decorators: [{
734
- type: Inject,
735
- args: [DOCUMENT]
736
- }] }] });
737
-
738
- /*
739
- * Copyright (c) Microsoft Corporation. All rights reserved.
740
- * Licensed under the MIT License.
741
- */
742
- /**
743
- * This is a dedicated redirect component to be added to Angular apps to
744
- * handle redirects when using @azure/msal-angular.
745
- * Import this component to use redirects in your app.
746
- */
747
- class MsalRedirectComponent {
748
- constructor(authService) {
749
- this.authService = authService;
750
- }
751
- ngOnInit() {
752
- this.authService.getLogger().verbose("MsalRedirectComponent activated", "");
753
- this.authService.handleRedirectObservable().subscribe();
754
- }
755
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalRedirectComponent, deps: [{ token: MsalService }], target: i0.ɵɵFactoryTarget.Component }); }
756
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "22.1.2", type: MsalRedirectComponent, isStandalone: false, selector: "app-redirect", ngImport: i0, template: "", isInline: true }); }
757
- }
758
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalRedirectComponent, decorators: [{
759
- type: Component,
760
- args: [{
761
- selector: "app-redirect",
762
- template: "",
763
- standalone: false,
764
- }]
765
- }], ctorParameters: () => [{ type: MsalService }] });
766
-
767
- /*
768
- * Copyright (c) Microsoft Corporation. All rights reserved.
769
- * Licensed under the MIT License.
770
- */
771
- class MsalModule {
772
- static forRoot(msalInstance, guardConfig, interceptorConfig) {
773
- return {
774
- ngModule: MsalModule,
775
- providers: [
776
- {
777
- provide: MSAL_INSTANCE,
778
- useValue: msalInstance,
779
- },
780
- {
781
- provide: MSAL_GUARD_CONFIG,
782
- useValue: guardConfig,
783
- },
784
- {
785
- provide: MSAL_INTERCEPTOR_CONFIG,
786
- useValue: interceptorConfig,
787
- },
788
- MsalService,
789
- ],
790
- };
791
- }
792
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
793
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "22.1.2", ngImport: i0, type: MsalModule, declarations: [MsalRedirectComponent], imports: [CommonModule] }); }
794
- static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalModule, providers: [MsalGuard, MsalBroadcastService], imports: [CommonModule] }); }
795
- }
796
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalModule, decorators: [{
797
- type: NgModule,
798
- args: [{
799
- declarations: [MsalRedirectComponent],
800
- imports: [CommonModule],
801
- providers: [MsalGuard, MsalBroadcastService],
802
- }]
803
- }] });
804
-
805
- /*
806
- * Copyright (c) Microsoft Corporation. All rights reserved.
807
- * Licensed under the MIT License.
808
- */
809
- /**
810
- * Custom navigation used for Angular client-side navigation.
811
- * See performance doc for details:
812
- * https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-angular/docs/performance.md
813
- */
814
- class MsalCustomNavigationClient extends NavigationClient {
815
- constructor(authService, router, location) {
816
- super();
817
- this.authService = authService;
818
- this.router = router;
819
- this.location = location;
820
- }
821
- async navigateInternal(url, options) {
822
- this.authService.getLogger().trace("MsalCustomNavigationClient called", "");
823
- this.authService
824
- .getLogger()
825
- .verbose("MsalCustomNavigationClient - navigating", "");
826
- this.authService
827
- .getLogger()
828
- .verbosePii(`MsalCustomNavigationClient - navigating to url: ${url}`, "");
829
- // Prevent hash clearing from causing an issue with Client-side navigation after redirect is handled
830
- if (options.noHistory) {
831
- return super.navigateInternal(url, options);
832
- }
833
- else {
834
- // Normalizing newUrl if no query string
835
- const urlComponents = new URL(url);
836
- const newUrl = urlComponents.search
837
- ? `${urlComponents.pathname}${urlComponents.search}`
838
- : this.location.normalize(urlComponents.pathname);
839
- await this.router.navigateByUrl(newUrl, {
840
- replaceUrl: options.noHistory,
841
- });
842
- }
843
- return Promise.resolve(options.noHistory);
844
- }
845
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalCustomNavigationClient, deps: [{ token: MsalService }, { token: i4.Router }, { token: i3.Location }], target: i0.ɵɵFactoryTarget.Injectable }); }
846
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalCustomNavigationClient }); }
847
- }
848
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: MsalCustomNavigationClient, decorators: [{
849
- type: Injectable
850
- }], ctorParameters: () => [{ type: MsalService }, { type: i4.Router }, { type: i3.Location }] });
851
-
852
- /*
853
- * Copyright (c) Microsoft Corporation. All rights reserved.
854
- * Licensed under the MIT License.
855
- */
856
- /**
857
- * @packageDocumentation
858
- * @module @azure/msal-angular
859
- */
860
-
861
- /**
862
- * Generated bundle index. Do not edit.
863
- */
864
-
15
+ var MsalBroadcastService = class MsalBroadcastService {
16
+ constructor(msalInstance, ngZone, msalBroadcastConfig) {
17
+ this.msalInstance = msalInstance;
18
+ this.ngZone = ngZone;
19
+ this.msalBroadcastConfig = msalBroadcastConfig;
20
+ if (this.msalBroadcastConfig && this.msalBroadcastConfig.eventsToReplay > 0) {
21
+ this.msalInstance.getLogger().clone(name, version).verbose(`BroadcastService - eventsToReplay set on BroadcastConfig, replaying the last ${this.msalBroadcastConfig.eventsToReplay} events`, "");
22
+ this._msalSubject = new ReplaySubject(this.msalBroadcastConfig.eventsToReplay);
23
+ } else this._msalSubject = new Subject();
24
+ this.msalSubject$ = this._msalSubject.asObservable();
25
+ this._inProgress = new BehaviorSubject(InteractionStatus.Startup);
26
+ this.inProgress$ = this._inProgress.asObservable();
27
+ this.msalInstance.addEventCallback((message) => {
28
+ this.ngZone.run(() => {
29
+ this._msalSubject.next(message);
30
+ const status = EventMessageUtils.getInteractionStatusFromEvent(message, this._inProgress.value);
31
+ if (status !== null) {
32
+ this.msalInstance.getLogger().clone(name, version).verbose(`BroadcastService - ${message.eventType} results in setting inProgress from ${this._inProgress.value} to ${status}`, "");
33
+ this._inProgress.next(status);
34
+ }
35
+ });
36
+ });
37
+ }
38
+ resetInProgressEvent() {
39
+ if (this._inProgress.value === InteractionStatus.Startup) this._inProgress.next(InteractionStatus.None);
40
+ }
41
+ static {
42
+ this.ɵfac = i0.ɵɵngDeclareFactory({
43
+ minVersion: "12.0.0",
44
+ version: "22.2.1",
45
+ ngImport: i0,
46
+ type: MsalBroadcastService,
47
+ deps: [
48
+ { token: MSAL_INSTANCE },
49
+ { token: i0.NgZone },
50
+ {
51
+ token: MSAL_BROADCAST_CONFIG,
52
+ optional: true
53
+ }
54
+ ],
55
+ target: i0.ɵɵFactoryTarget.Injectable
56
+ });
57
+ }
58
+ static {
59
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
60
+ minVersion: "12.0.0",
61
+ version: "22.2.1",
62
+ ngImport: i0,
63
+ type: MsalBroadcastService
64
+ });
65
+ }
66
+ };
67
+ i0.ɵɵngDeclareClassMetadata({
68
+ minVersion: "12.0.0",
69
+ version: "22.2.1",
70
+ ngImport: i0,
71
+ type: MsalBroadcastService,
72
+ decorators: [{ type: Injectable }],
73
+ ctorParameters: () => [
74
+ {
75
+ type: void 0,
76
+ decorators: [{
77
+ type: Inject,
78
+ args: [MSAL_INSTANCE]
79
+ }]
80
+ },
81
+ { type: i0.NgZone },
82
+ {
83
+ type: void 0,
84
+ decorators: [{ type: Optional }, {
85
+ type: Inject,
86
+ args: [MSAL_BROADCAST_CONFIG]
87
+ }]
88
+ }
89
+ ]
90
+ });
91
+ var MsalService = class MsalService {
92
+ constructor(instance, location, injector) {
93
+ this.instance = instance;
94
+ this.location = location;
95
+ this.injector = injector;
96
+ const hash = this.location.path(true).split("#").pop();
97
+ if (hash) this.redirectHash = `#${hash}`;
98
+ this.instance.initializeWrapperLibrary(WrapperSKU.Angular, version);
99
+ }
100
+ initialize() {
101
+ return from(this.instance.initialize());
102
+ }
103
+ withInitialize(call) {
104
+ return from(this.instance.initialize().then(() => call()));
105
+ }
106
+ acquireTokenPopup(request) {
107
+ return this.withInitialize(() => this.instance.acquireTokenPopup(request));
108
+ }
109
+ acquireTokenRedirect(request) {
110
+ return this.withInitialize(() => this.instance.acquireTokenRedirect(request));
111
+ }
112
+ acquireTokenSilent(silentRequest) {
113
+ return this.withInitialize(() => this.instance.acquireTokenSilent(silentRequest));
114
+ }
115
+ handleRedirectObservable(hashOrOptions) {
116
+ const options = typeof hashOrOptions === "string" ? { hash: hashOrOptions } : hashOrOptions || {};
117
+ const hash = options.hash || this.redirectHash;
118
+ const finalOptions = {
119
+ ...options,
120
+ ...hash ? { hash } : {}
121
+ };
122
+ return from(this.instance.initialize().then(() => this.instance.handleRedirectPromise(finalOptions)).finally(() => {
123
+ this.injector.get(MsalBroadcastService).resetInProgressEvent();
124
+ }));
125
+ }
126
+ loginPopup(request) {
127
+ return this.withInitialize(() => this.instance.loginPopup(request));
128
+ }
129
+ loginRedirect(request) {
130
+ return this.withInitialize(() => this.instance.loginRedirect(request));
131
+ }
132
+ logoutRedirect(logoutRequest) {
133
+ return this.withInitialize(() => this.instance.logoutRedirect(logoutRequest));
134
+ }
135
+ logoutPopup(logoutRequest) {
136
+ return this.withInitialize(() => this.instance.logoutPopup(logoutRequest));
137
+ }
138
+ ssoSilent(request) {
139
+ return this.withInitialize(() => this.instance.ssoSilent(request));
140
+ }
141
+ getLogger() {
142
+ if (!this.logger) this.logger = this.instance.getLogger().clone(name, version);
143
+ return this.logger;
144
+ }
145
+ setLogger(logger) {
146
+ this.logger = logger.clone(name, version);
147
+ this.instance.setLogger(logger);
148
+ }
149
+ static {
150
+ this.ɵfac = i0.ɵɵngDeclareFactory({
151
+ minVersion: "12.0.0",
152
+ version: "22.2.1",
153
+ ngImport: i0,
154
+ type: MsalService,
155
+ deps: [
156
+ { token: MSAL_INSTANCE },
157
+ { token: i1.Location },
158
+ { token: i0.Injector }
159
+ ],
160
+ target: i0.ɵɵFactoryTarget.Injectable
161
+ });
162
+ }
163
+ static {
164
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
165
+ minVersion: "12.0.0",
166
+ version: "22.2.1",
167
+ ngImport: i0,
168
+ type: MsalService
169
+ });
170
+ }
171
+ };
172
+ i0.ɵɵngDeclareClassMetadata({
173
+ minVersion: "12.0.0",
174
+ version: "22.2.1",
175
+ ngImport: i0,
176
+ type: MsalService,
177
+ decorators: [{ type: Injectable }],
178
+ ctorParameters: () => [
179
+ {
180
+ type: void 0,
181
+ decorators: [{
182
+ type: Inject,
183
+ args: [MSAL_INSTANCE]
184
+ }]
185
+ },
186
+ { type: i1.Location },
187
+ { type: i0.Injector }
188
+ ]
189
+ });
190
+ var MsalGuard = class MsalGuard {
191
+ constructor(msalGuardConfig, msalBroadcastService, authService, location, router) {
192
+ this.msalGuardConfig = msalGuardConfig;
193
+ this.msalBroadcastService = msalBroadcastService;
194
+ this.authService = authService;
195
+ this.location = location;
196
+ this.router = router;
197
+ this.msalBroadcastService.inProgress$.subscribe();
198
+ }
199
+ parseUrl(url) {
200
+ return this.router.parseUrl(url);
201
+ }
202
+ getDestinationUrl(path) {
203
+ this.authService.getLogger().verbose("Guard - getting destination url", "");
204
+ const baseElements = document.getElementsByTagName("base");
205
+ const baseUrl = this.location.normalize(baseElements.length ? baseElements[0].href : window.location.origin);
206
+ const pathUrl = this.location.prepareExternalUrl(path);
207
+ if (pathUrl.startsWith("#")) {
208
+ this.authService.getLogger().verbose("Guard - destination by hash routing", "");
209
+ return `${baseUrl}/${pathUrl}`;
210
+ }
211
+ return `${baseUrl}${path}`;
212
+ }
213
+ loginInteractively(state) {
214
+ const authRequest = typeof this.msalGuardConfig.authRequest === "function" ? this.msalGuardConfig.authRequest(this.authService, state) : { ...this.msalGuardConfig.authRequest };
215
+ if (this.msalGuardConfig.interactionType === InteractionType.Popup) {
216
+ this.authService.getLogger().verbose("Guard - logging in by popup", authRequest.correlationId ?? "");
217
+ return this.authService.loginPopup(authRequest).pipe(map((response) => {
218
+ this.authService.getLogger().verbose("Guard - login by popup successful, can activate, setting active account", authRequest.correlationId ?? "");
219
+ this.authService.instance.setActiveAccount(response.account);
220
+ return true;
221
+ }));
222
+ }
223
+ this.authService.getLogger().verbose("Guard - logging in by redirect", authRequest.correlationId ?? "");
224
+ const redirectStartPage = this.getDestinationUrl(state.url);
225
+ return this.authService.loginRedirect({
226
+ redirectStartPage,
227
+ ...authRequest
228
+ }).pipe(map(() => false));
229
+ }
230
+ activateHelper(state) {
231
+ if (this.msalGuardConfig.interactionType !== InteractionType.Popup && this.msalGuardConfig.interactionType !== InteractionType.Redirect) throw new BrowserConfigurationAuthError("invalid_interaction_type", "", "Invalid interaction type provided to MSAL Guard. InteractionType.Popup or InteractionType.Redirect must be provided in the MsalGuardConfiguration");
232
+ this.authService.getLogger().verbose("MSAL Guard activated", "");
233
+ if (typeof window === "undefined") {
234
+ this.authService.getLogger().info("Guard - window is undefined, MSAL does not support server-side token acquisition", "");
235
+ return of(true);
236
+ } else try {
237
+ BrowserUtils.blockReloadInHiddenIframes();
238
+ } catch (error) {
239
+ if (!this.authService.instance.getConfiguration().system.allowRedirectInIframe) {
240
+ this.authService.getLogger().warning("Guard - redirectUri set to page with MSAL Guard. It is recommended to not set redirectUri to a page that requires authentication.", "");
241
+ return of(false);
242
+ }
243
+ }
244
+ if (this.msalGuardConfig.loginFailedRoute) this.loginFailedRoute = this.parseUrl(this.msalGuardConfig.loginFailedRoute);
245
+ const currentPath = this.location.path(true);
246
+ return this.authService.initialize().pipe(concatMap(() => {
247
+ return this.authService.handleRedirectObservable();
248
+ }), concatMap(() => {
249
+ if (!this.authService.instance.getAllAccounts().length) {
250
+ if (state) {
251
+ this.authService.getLogger().verbose("Guard - no accounts retrieved, log in required to activate", "");
252
+ return this.loginInteractively(state);
253
+ }
254
+ this.authService.getLogger().verbose("Guard - no accounts retrieved, no state, cannot load", "");
255
+ return of(false);
256
+ }
257
+ this.authService.getLogger().verbose("Guard - at least 1 account exists, can activate or load", "");
258
+ if (state) {
259
+ const urlContainsCode = this.includesCode(state.url);
260
+ const fragmentContainsCode = !!state.root && !!state.root.fragment && this.includesCode(`#${state.root.fragment}`);
261
+ const hashRouting = this.location.prepareExternalUrl(state.url).indexOf("#") === 0;
262
+ if (urlContainsCode && (fragmentContainsCode || hashRouting)) {
263
+ this.authService.getLogger().info("Guard - Hash contains known code response, stopping navigation.", "");
264
+ if (currentPath.indexOf("#") > -1) return of(this.parseUrl(this.location.path()));
265
+ return of(this.parseUrl(""));
266
+ }
267
+ }
268
+ return of(true);
269
+ }), catchError((error) => {
270
+ this.authService.getLogger().error("Guard - error while logging in, unable to activate", "");
271
+ this.authService.getLogger().errorPii(`Guard - error: ${error.message}`, "");
272
+ if (this.loginFailedRoute && state) {
273
+ this.authService.getLogger().verbose("Guard - loginFailedRoute set, redirecting", "");
274
+ return of(this.loginFailedRoute);
275
+ }
276
+ return of(false);
277
+ }));
278
+ }
279
+ includesCode(path) {
280
+ return path.lastIndexOf("/code") > -1 && path.lastIndexOf("/code") === path.length - 5 || path.indexOf("#code=") > -1 || path.indexOf("&code=") > -1;
281
+ }
282
+ canActivate(route, state) {
283
+ this.authService.getLogger().verbose("Guard - canActivate", "");
284
+ return this.activateHelper(state);
285
+ }
286
+ canActivateChild(route, state) {
287
+ this.authService.getLogger().verbose("Guard - canActivateChild", "");
288
+ return this.activateHelper(state);
289
+ }
290
+ canMatch() {
291
+ this.authService.getLogger().verbose("Guard - canLoad", "");
292
+ return this.activateHelper();
293
+ }
294
+ static {
295
+ this.ɵfac = i0.ɵɵngDeclareFactory({
296
+ minVersion: "12.0.0",
297
+ version: "22.2.1",
298
+ ngImport: i0,
299
+ type: MsalGuard,
300
+ deps: [
301
+ { token: MSAL_GUARD_CONFIG },
302
+ { token: MsalBroadcastService },
303
+ { token: MsalService },
304
+ { token: i1.Location },
305
+ { token: i4.Router }
306
+ ],
307
+ target: i0.ɵɵFactoryTarget.Injectable
308
+ });
309
+ }
310
+ static {
311
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
312
+ minVersion: "12.0.0",
313
+ version: "22.2.1",
314
+ ngImport: i0,
315
+ type: MsalGuard
316
+ });
317
+ }
318
+ };
319
+ i0.ɵɵngDeclareClassMetadata({
320
+ minVersion: "12.0.0",
321
+ version: "22.2.1",
322
+ ngImport: i0,
323
+ type: MsalGuard,
324
+ decorators: [{ type: Injectable }],
325
+ ctorParameters: () => [
326
+ {
327
+ type: void 0,
328
+ decorators: [{
329
+ type: Inject,
330
+ args: [MSAL_GUARD_CONFIG]
331
+ }]
332
+ },
333
+ { type: MsalBroadcastService },
334
+ { type: MsalService },
335
+ { type: i1.Location },
336
+ { type: i4.Router }
337
+ ]
338
+ });
339
+ var MsalInterceptor = class MsalInterceptor {
340
+ constructor(msalInterceptorConfig, authService, location, msalBroadcastService, document) {
341
+ this.msalInterceptorConfig = msalInterceptorConfig;
342
+ this.authService = authService;
343
+ this.location = location;
344
+ this.msalBroadcastService = msalBroadcastService;
345
+ this._document = document;
346
+ if (this.msalInterceptorConfig.strictMatching === void 0) this.authService.getLogger().warning(`[MSAL] strictMatching is enabled by default. See: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/msal-interceptor.md#strict-matching-strictmatching`, "");
347
+ }
348
+ intercept(req, next) {
349
+ if (this.msalInterceptorConfig.interactionType !== InteractionType.Popup && this.msalInterceptorConfig.interactionType !== InteractionType.Redirect) throw new BrowserConfigurationAuthError("invalid_interaction_type", "", "Invalid interaction type provided to MSAL Interceptor. InteractionType.Popup, InteractionType.Redirect must be provided in the msalInterceptorConfiguration");
350
+ this.authService.getLogger().verbose("MSAL Interceptor activated", "");
351
+ const scopes = this.getScopesForEndpoint(req.url, req.method);
352
+ if (!scopes || scopes.length === 0) {
353
+ this.authService.getLogger().verbose("Interceptor - no scopes for endpoint", "");
354
+ return next.handle(req);
355
+ }
356
+ let account;
357
+ const activeAccount = this.authService.instance.getActiveAccount();
358
+ if (activeAccount) {
359
+ this.authService.getLogger().verbose("Interceptor - active account selected", "");
360
+ account = activeAccount;
361
+ } else {
362
+ this.authService.getLogger().verbose("Interceptor - no active account, fallback to first account", "");
363
+ account = this.authService.instance.getAllAccounts()[0];
364
+ }
365
+ const authRequest = typeof this.msalInterceptorConfig.authRequest === "function" ? this.msalInterceptorConfig.authRequest(this.authService, req, { account }) : {
366
+ ...this.msalInterceptorConfig.authRequest,
367
+ account
368
+ };
369
+ this.authService.getLogger().info(`Interceptor - ${scopes.length} scopes found for endpoint`, "");
370
+ this.authService.getLogger().infoPii(`Interceptor - [${scopes}] scopes found for ${req.url}`, "");
371
+ return this.acquireToken(authRequest, scopes, account).pipe(switchMap((result) => {
372
+ this.authService.getLogger().verbose("Interceptor - setting authorization headers", "");
373
+ const headers = req.headers.set("Authorization", `Bearer ${result.accessToken}`);
374
+ const requestClone = req.clone({ headers });
375
+ return next.handle(requestClone);
376
+ }));
377
+ }
378
+ acquireToken(authRequest, scopes, account) {
379
+ return this.authService.acquireTokenSilent({
380
+ ...authRequest,
381
+ scopes,
382
+ account
383
+ }).pipe(catchError(() => {
384
+ this.authService.getLogger().error("Interceptor - acquireTokenSilent rejected with error. Invoking interaction to resolve.", authRequest.correlationId ?? "");
385
+ return this.msalBroadcastService.inProgress$.pipe(take(1), switchMap((status) => {
386
+ if (status === InteractionStatus.None) return this.acquireTokenInteractively(authRequest, scopes);
387
+ return this.msalBroadcastService.inProgress$.pipe(filter((status) => status === InteractionStatus.None), take(1), switchMap(() => this.acquireToken(authRequest, scopes, account)));
388
+ }));
389
+ }), switchMap((result) => {
390
+ if (!result.accessToken) {
391
+ this.authService.getLogger().error("Interceptor - acquireTokenSilent resolved with null access token. Known issue with B2C tenants, invoking interaction to resolve.", authRequest.correlationId ?? "");
392
+ return this.msalBroadcastService.inProgress$.pipe(filter((status) => status === InteractionStatus.None), take(1), switchMap(() => this.acquireTokenInteractively(authRequest, scopes)));
393
+ }
394
+ return of(result);
395
+ }));
396
+ }
397
+ acquireTokenInteractively(authRequest, scopes) {
398
+ if (this.msalInterceptorConfig.interactionType === InteractionType.Popup) {
399
+ this.authService.getLogger().verbose("Interceptor - error acquiring token silently, acquiring by popup", authRequest.correlationId ?? "");
400
+ return this.authService.acquireTokenPopup({
401
+ ...authRequest,
402
+ scopes
403
+ });
404
+ }
405
+ this.authService.getLogger().verbose("Interceptor - error acquiring token silently, acquiring by redirect", authRequest.correlationId ?? "");
406
+ const redirectStartPage = window.location.href;
407
+ this.authService.acquireTokenRedirect({
408
+ ...authRequest,
409
+ scopes,
410
+ redirectStartPage
411
+ });
412
+ return EMPTY;
413
+ }
414
+ getScopesForEndpoint(endpoint, httpMethod) {
415
+ this.authService.getLogger().verbose("Interceptor - getting scopes for endpoint", "");
416
+ const normalizedEndpoint = this.location.normalize(endpoint);
417
+ const protectedResourcesArray = Array.from(this.msalInterceptorConfig.protectedResourceMap.keys());
418
+ const matchingProtectedResources = this.matchResourcesToEndpoint(protectedResourcesArray, normalizedEndpoint);
419
+ if (matchingProtectedResources.length > 0) return this.matchScopesToEndpoint(this.msalInterceptorConfig.protectedResourceMap, matchingProtectedResources, httpMethod);
420
+ return null;
421
+ }
422
+ matchResourcesToEndpoint(protectedResourcesEndpoints, endpoint) {
423
+ const matchingResources = [];
424
+ protectedResourcesEndpoints.forEach((key) => {
425
+ const normalizedKey = this.location.normalize(key);
426
+ const absoluteKey = this.getAbsoluteUrl(normalizedKey);
427
+ const keyComponents = new URL(absoluteKey);
428
+ const absoluteEndpoint = this.getAbsoluteUrl(endpoint);
429
+ const endpointComponents = new URL(absoluteEndpoint);
430
+ if (this.checkUrlComponents(keyComponents, endpointComponents)) matchingResources.push(key);
431
+ });
432
+ return matchingResources;
433
+ }
434
+ checkUrlComponents(keyComponents, endpointComponents) {
435
+ const urlProperties = [
436
+ "protocol",
437
+ "host",
438
+ "pathname",
439
+ "search",
440
+ "hash"
441
+ ];
442
+ const componentMap = {
443
+ protocol: "protocol",
444
+ host: "host",
445
+ pathname: "path",
446
+ search: "search",
447
+ hash: "hash"
448
+ };
449
+ const useStrictMatching = this.msalInterceptorConfig.strictMatching !== false;
450
+ for (const property of urlProperties) if (keyComponents[property]) {
451
+ const decodedInput = decodeURIComponent(keyComponents[property]);
452
+ if (useStrictMatching) {
453
+ const component = componentMap[property];
454
+ if (!this.matchPatternStrict(decodedInput, endpointComponents[property], component)) return false;
455
+ } else if (!this.matchPattern(decodedInput, endpointComponents[property])) return false;
456
+ }
457
+ return true;
458
+ }
459
+ getAbsoluteUrl(url) {
460
+ const link = this._document.createElement("a");
461
+ link.href = url;
462
+ return link.href;
463
+ }
464
+ matchScopesToEndpoint(protectedResourceMap, endpointArray, httpMethod) {
465
+ const allMatchedScopes = [];
466
+ endpointArray.forEach((matchedEndpoint) => {
467
+ const scopesForEndpoint = [];
468
+ const methodAndScopesArray = protectedResourceMap.get(matchedEndpoint);
469
+ if (methodAndScopesArray === null) {
470
+ allMatchedScopes.push(null);
471
+ return;
472
+ }
473
+ if (methodAndScopesArray === void 0) return;
474
+ methodAndScopesArray.forEach((entry) => {
475
+ if (typeof entry === "string") scopesForEndpoint.push(entry);
476
+ else {
477
+ const normalizedRequestMethod = httpMethod.toLowerCase();
478
+ if (entry.httpMethod.toLowerCase() === normalizedRequestMethod) {
479
+ if (entry.scopes === null) allMatchedScopes.push(null);
480
+ else entry.scopes.forEach((scope) => {
481
+ scopesForEndpoint.push(scope);
482
+ });
483
+ }
484
+ }
485
+ });
486
+ if (scopesForEndpoint.length > 0) allMatchedScopes.push(scopesForEndpoint);
487
+ });
488
+ if (allMatchedScopes.length > 0) {
489
+ if (allMatchedScopes.length > 1) this.authService.getLogger().warning("Interceptor - More than 1 matching scopes for endpoint found.", "");
490
+ return allMatchedScopes[0];
491
+ }
492
+ return null;
493
+ }
494
+ matchPattern(pattern, input) {
495
+ return new RegExp(pattern.replace(/\\/g, "\\\\").replace(/\*/g, "[^ ]*").replace(/\?/g, "\\?")).test(input);
496
+ }
497
+ matchPatternStrict(pattern, input, component) {
498
+ let regexBody = pattern.replace(/[.+^${}()|[\]\\*?]/g, "\\$&");
499
+ if (component === "host") regexBody = regexBody.replace(/\\\*/g, "[^.]*");
500
+ else regexBody = regexBody.replace(/\\\*/g, ".*");
501
+ return new RegExp(`^${regexBody}$`).test(input);
502
+ }
503
+ static {
504
+ this.ɵfac = i0.ɵɵngDeclareFactory({
505
+ minVersion: "12.0.0",
506
+ version: "22.2.1",
507
+ ngImport: i0,
508
+ type: MsalInterceptor,
509
+ deps: [
510
+ { token: MSAL_INTERCEPTOR_CONFIG },
511
+ { token: MsalService },
512
+ { token: i1.Location },
513
+ { token: MsalBroadcastService },
514
+ { token: DOCUMENT }
515
+ ],
516
+ target: i0.ɵɵFactoryTarget.Injectable
517
+ });
518
+ }
519
+ static {
520
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
521
+ minVersion: "12.0.0",
522
+ version: "22.2.1",
523
+ ngImport: i0,
524
+ type: MsalInterceptor
525
+ });
526
+ }
527
+ };
528
+ i0.ɵɵngDeclareClassMetadata({
529
+ minVersion: "12.0.0",
530
+ version: "22.2.1",
531
+ ngImport: i0,
532
+ type: MsalInterceptor,
533
+ decorators: [{ type: Injectable }],
534
+ ctorParameters: () => [
535
+ {
536
+ type: void 0,
537
+ decorators: [{
538
+ type: Inject,
539
+ args: [MSAL_INTERCEPTOR_CONFIG]
540
+ }]
541
+ },
542
+ { type: MsalService },
543
+ { type: i1.Location },
544
+ { type: MsalBroadcastService },
545
+ {
546
+ type: Document,
547
+ decorators: [{
548
+ type: Inject,
549
+ args: [DOCUMENT]
550
+ }]
551
+ }
552
+ ]
553
+ });
554
+ var MsalRedirectComponent = class MsalRedirectComponent {
555
+ constructor(authService) {
556
+ this.authService = authService;
557
+ }
558
+ ngOnInit() {
559
+ this.authService.getLogger().verbose("MsalRedirectComponent activated", "");
560
+ this.authService.handleRedirectObservable().subscribe();
561
+ }
562
+ static {
563
+ this.ɵfac = i0.ɵɵngDeclareFactory({
564
+ minVersion: "12.0.0",
565
+ version: "22.2.1",
566
+ ngImport: i0,
567
+ type: MsalRedirectComponent,
568
+ deps: [{ token: MsalService }],
569
+ target: i0.ɵɵFactoryTarget.Component
570
+ });
571
+ }
572
+ static {
573
+ this.ɵcmp = i0.ɵɵngDeclareComponent({
574
+ minVersion: "14.0.0",
575
+ version: "22.2.1",
576
+ type: MsalRedirectComponent,
577
+ isStandalone: false,
578
+ selector: "app-redirect",
579
+ ngImport: i0,
580
+ template: "",
581
+ isInline: true
582
+ });
583
+ }
584
+ };
585
+ i0.ɵɵngDeclareClassMetadata({
586
+ minVersion: "12.0.0",
587
+ version: "22.2.1",
588
+ ngImport: i0,
589
+ type: MsalRedirectComponent,
590
+ decorators: [{
591
+ type: Component,
592
+ args: [{
593
+ selector: "app-redirect",
594
+ template: "",
595
+ standalone: false
596
+ }]
597
+ }],
598
+ ctorParameters: () => [{ type: MsalService }]
599
+ });
600
+ var MsalModule = class MsalModule {
601
+ static forRoot(msalInstance, guardConfig, interceptorConfig) {
602
+ return {
603
+ ngModule: MsalModule,
604
+ providers: [
605
+ {
606
+ provide: MSAL_INSTANCE,
607
+ useValue: msalInstance
608
+ },
609
+ {
610
+ provide: MSAL_GUARD_CONFIG,
611
+ useValue: guardConfig
612
+ },
613
+ {
614
+ provide: MSAL_INTERCEPTOR_CONFIG,
615
+ useValue: interceptorConfig
616
+ },
617
+ MsalService
618
+ ]
619
+ };
620
+ }
621
+ static {
622
+ this.ɵfac = i0.ɵɵngDeclareFactory({
623
+ minVersion: "12.0.0",
624
+ version: "22.2.1",
625
+ ngImport: i0,
626
+ type: MsalModule,
627
+ deps: [],
628
+ target: i0.ɵɵFactoryTarget.NgModule
629
+ });
630
+ }
631
+ static {
632
+ this.ɵmod = i0.ɵɵngDeclareNgModule({
633
+ minVersion: "14.0.0",
634
+ version: "22.2.1",
635
+ ngImport: i0,
636
+ type: MsalModule,
637
+ declarations: [MsalRedirectComponent],
638
+ imports: [CommonModule]
639
+ });
640
+ }
641
+ static {
642
+ this.ɵinj = i0.ɵɵngDeclareInjector({
643
+ minVersion: "12.0.0",
644
+ version: "22.2.1",
645
+ ngImport: i0,
646
+ type: MsalModule,
647
+ providers: [MsalGuard, MsalBroadcastService],
648
+ imports: [CommonModule]
649
+ });
650
+ }
651
+ };
652
+ i0.ɵɵngDeclareClassMetadata({
653
+ minVersion: "12.0.0",
654
+ version: "22.2.1",
655
+ ngImport: i0,
656
+ type: MsalModule,
657
+ decorators: [{
658
+ type: NgModule,
659
+ args: [{
660
+ declarations: [MsalRedirectComponent],
661
+ imports: [CommonModule],
662
+ providers: [MsalGuard, MsalBroadcastService]
663
+ }]
664
+ }]
665
+ });
666
+ var MsalCustomNavigationClient = class MsalCustomNavigationClient extends NavigationClient {
667
+ constructor(authService, router, location) {
668
+ super();
669
+ this.authService = authService;
670
+ this.router = router;
671
+ this.location = location;
672
+ }
673
+ async navigateInternal(url, options) {
674
+ this.authService.getLogger().trace("MsalCustomNavigationClient called", "");
675
+ this.authService.getLogger().verbose("MsalCustomNavigationClient - navigating", "");
676
+ this.authService.getLogger().verbosePii(`MsalCustomNavigationClient - navigating to url: ${url}`, "");
677
+ if (options.noHistory) return super.navigateInternal(url, options);
678
+ else {
679
+ const urlComponents = new URL(url);
680
+ const newUrl = urlComponents.search ? `${urlComponents.pathname}${urlComponents.search}` : this.location.normalize(urlComponents.pathname);
681
+ await this.router.navigateByUrl(newUrl, { replaceUrl: options.noHistory });
682
+ }
683
+ return Promise.resolve(options.noHistory);
684
+ }
685
+ static {
686
+ this.ɵfac = i0.ɵɵngDeclareFactory({
687
+ minVersion: "12.0.0",
688
+ version: "22.2.1",
689
+ ngImport: i0,
690
+ type: MsalCustomNavigationClient,
691
+ deps: [
692
+ { token: MsalService },
693
+ { token: i4.Router },
694
+ { token: i1.Location }
695
+ ],
696
+ target: i0.ɵɵFactoryTarget.Injectable
697
+ });
698
+ }
699
+ static {
700
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
701
+ minVersion: "12.0.0",
702
+ version: "22.2.1",
703
+ ngImport: i0,
704
+ type: MsalCustomNavigationClient
705
+ });
706
+ }
707
+ };
708
+ i0.ɵɵngDeclareClassMetadata({
709
+ minVersion: "12.0.0",
710
+ version: "22.2.1",
711
+ ngImport: i0,
712
+ type: MsalCustomNavigationClient,
713
+ decorators: [{ type: Injectable }],
714
+ ctorParameters: () => [
715
+ { type: MsalService },
716
+ { type: i4.Router },
717
+ { type: i1.Location }
718
+ ]
719
+ });
865
720
  export { MSAL_BROADCAST_CONFIG, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalBroadcastService, MsalCustomNavigationClient, MsalGuard, MsalInterceptor, MsalModule, MsalRedirectComponent, MsalService, version };
866
- //# sourceMappingURL=azure-msal-angular.mjs.map
721
+
722
+ //# sourceMappingURL=azure-msal-angular.mjs.map