-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathmsal.interceptor.ts
More file actions
496 lines (452 loc) · 16.1 KB
/
Copy pathmsal.interceptor.ts
File metadata and controls
496 lines (452 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { Injectable, Inject } from "@angular/core";
import { Location, DOCUMENT } from "@angular/common";
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
} from "@angular/common/http"; // eslint-disable-line import/no-unresolved
import {
AccountInfo,
AuthenticationResult,
BrowserConfigurationAuthError,
InteractionStatus,
InteractionType,
} from "@azure/msal-browser";
import { Observable, EMPTY, of } from "rxjs";
import { switchMap, catchError, take, filter } from "rxjs/operators";
import { MsalService } from "./msal.service";
import {
MsalInterceptorAuthRequest,
MsalInterceptorConfiguration,
ProtectedResourceScopes,
} from "./msal.interceptor.config";
import { MsalBroadcastService } from "./msal.broadcast.service";
import { MSAL_INTERCEPTOR_CONFIG } from "./constants";
@Injectable()
export class MsalInterceptor implements HttpInterceptor {
private _document?: Document;
constructor(
@Inject(MSAL_INTERCEPTOR_CONFIG)
private msalInterceptorConfig: MsalInterceptorConfiguration,
private authService: MsalService,
private location: Location,
private msalBroadcastService: MsalBroadcastService,
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
@Inject(DOCUMENT) document?: any
) {
this._document = document as Document;
if (this.msalInterceptorConfig.strictMatching === undefined) {
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`,
""
);
}
}
intercept(
req: HttpRequest<any>, // eslint-disable-line @typescript-eslint/no-explicit-any
next: HttpHandler
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Observable<HttpEvent<any>> {
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"
);
}
this.authService.getLogger().verbose("MSAL Interceptor activated", "");
const scopes = this.getScopesForEndpoint(req.url, req.method);
// If no scopes for endpoint, does not acquire token
if (!scopes || scopes.length === 0) {
this.authService
.getLogger()
.verbose("Interceptor - no scopes for endpoint", "");
return next.handle(req);
}
// Sets account as active account or first account
let account: AccountInfo;
if (!!this.authService.instance.getActiveAccount()) {
this.authService
.getLogger()
.verbose("Interceptor - active account selected", "");
account = this.authService.instance.getActiveAccount();
} else {
this.authService
.getLogger()
.verbose(
"Interceptor - no active account, fallback to first account",
""
);
account = this.authService.instance.getAllAccounts()[0];
}
const authRequest =
typeof this.msalInterceptorConfig.authRequest === "function"
? this.msalInterceptorConfig.authRequest(this.authService, req, {
account: account,
})
: { ...this.msalInterceptorConfig.authRequest, account };
this.authService
.getLogger()
.info(`Interceptor - ${scopes.length} scopes found for endpoint`, "");
this.authService
.getLogger()
.infoPii(`Interceptor - [${scopes}] scopes found for ${req.url}`, "");
return this.acquireToken(authRequest, scopes, account).pipe(
switchMap((result: AuthenticationResult) => {
this.authService
.getLogger()
.verbose("Interceptor - setting authorization headers", "");
const headers = req.headers.set(
"Authorization",
`Bearer ${result.accessToken}`
);
const requestClone = req.clone({ headers });
return next.handle(requestClone);
})
);
}
/**
* Try to acquire token silently. Invoke interaction if acquireTokenSilent rejected with error or resolved with null access token
* @param authRequest Request
* @param scopes Array of scopes for the request
* @param account Account
* @returns Authentication result
*/
private acquireToken(
authRequest: MsalInterceptorAuthRequest,
scopes: string[],
account: AccountInfo
): Observable<AuthenticationResult> {
// Note: For MSA accounts, include openid scope when calling acquireTokenSilent to return idToken
return this.authService
.acquireTokenSilent({ ...authRequest, scopes, account })
.pipe(
catchError(() => {
this.authService
.getLogger()
.error(
"Interceptor - acquireTokenSilent rejected with error. Invoking interaction to resolve.",
authRequest.correlationId
);
return this.msalBroadcastService.inProgress$.pipe(
take(1),
switchMap((status: InteractionStatus) => {
if (status === InteractionStatus.None) {
return this.acquireTokenInteractively(authRequest, scopes);
}
return this.msalBroadcastService.inProgress$.pipe(
filter(
(status: InteractionStatus) =>
status === InteractionStatus.None
),
take(1),
switchMap(() => this.acquireToken(authRequest, scopes, account))
);
})
);
}),
switchMap((result: AuthenticationResult) => {
if (!result.accessToken) {
this.authService
.getLogger()
.error(
"Interceptor - acquireTokenSilent resolved with null access token. Known issue with B2C tenants, invoking interaction to resolve.",
authRequest.correlationId
);
return this.msalBroadcastService.inProgress$.pipe(
filter(
(status: InteractionStatus) => status === InteractionStatus.None
),
take(1),
switchMap(() =>
this.acquireTokenInteractively(authRequest, scopes)
)
);
}
return of(result);
})
);
}
/**
* Invoke interaction for the given set of scopes
* @param authRequest Request
* @param scopes Array of scopes for the request
* @returns Result from the interactive request
*/
private acquireTokenInteractively(
authRequest: MsalInterceptorAuthRequest,
scopes: string[]
): Observable<AuthenticationResult> {
if (this.msalInterceptorConfig.interactionType === InteractionType.Popup) {
this.authService
.getLogger()
.verbose(
"Interceptor - error acquiring token silently, acquiring by popup",
authRequest.correlationId
);
return this.authService.acquireTokenPopup({ ...authRequest, scopes });
}
this.authService
.getLogger()
.verbose(
"Interceptor - error acquiring token silently, acquiring by redirect",
authRequest.correlationId
);
const redirectStartPage = window.location.href;
this.authService.acquireTokenRedirect({
...authRequest,
scopes,
redirectStartPage,
});
return EMPTY;
}
/**
* Looks up the scopes for the given endpoint from the protectedResourceMap
* @param endpoint Url of the request
* @param httpMethod Http method of the request
* @returns Array of scopes, or null if not found
*
*/
private getScopesForEndpoint(
endpoint: string,
httpMethod: string
): Array<string> | null {
this.authService
.getLogger()
.verbose("Interceptor - getting scopes for endpoint", "");
// Ensures endpoints and protected resources compared are normalized
const normalizedEndpoint = this.location.normalize(endpoint);
const protectedResourcesArray = Array.from(
this.msalInterceptorConfig.protectedResourceMap.keys()
);
const matchingProtectedResources = this.matchResourcesToEndpoint(
protectedResourcesArray,
normalizedEndpoint
);
if (matchingProtectedResources.length > 0) {
return this.matchScopesToEndpoint(
this.msalInterceptorConfig.protectedResourceMap,
matchingProtectedResources,
httpMethod
);
}
return null;
}
/**
* Finds resource endpoints that match request endpoint
* @param protectedResourcesEndpoints
* @param endpoint
* @returns
*/
private matchResourcesToEndpoint(
protectedResourcesEndpoints: string[],
endpoint: string
): Array<string> {
const matchingResources: Array<string> = [];
protectedResourcesEndpoints.forEach((key) => {
const normalizedKey = this.location.normalize(key);
// Get url components
const absoluteKey = this.getAbsoluteUrl(normalizedKey);
const keyComponents = new URL(absoluteKey);
const absoluteEndpoint = this.getAbsoluteUrl(endpoint);
const endpointComponents = new URL(absoluteEndpoint);
if (this.checkUrlComponents(keyComponents, endpointComponents)) {
matchingResources.push(key);
}
});
return matchingResources;
}
/**
* Compares URL segments between key and endpoint
* @param key
* @param endpoint
* @returns
*/
private checkUrlComponents(
keyComponents: URL,
endpointComponents: URL
): boolean {
// URL properties from https://developer.mozilla.org/en-US/docs/Web/API/URL
const urlProperties = ["protocol", "host", "pathname", "search", "hash"];
// Maps URL property names to the component identifiers used by matchPatternStrict.
const componentMap: Record<
string,
"protocol" | "host" | "path" | "search" | "hash"
> = {
protocol: "protocol",
host: "host",
pathname: "path",
search: "search",
hash: "hash",
};
const useStrictMatching =
this.msalInterceptorConfig.strictMatching !== false;
for (const property of urlProperties) {
if (keyComponents[property]) {
const decodedInput = decodeURIComponent(keyComponents[property]);
if (useStrictMatching) {
/*
* Strict matching (v5 default): anchored patterns, metacharacters
* are treated as literals, host wildcards do not span dot separators.
*/
const component = componentMap[property];
if (
!this.matchPatternStrict(
decodedInput,
endpointComponents[property],
component
)
) {
return false;
}
} else {
// Legacy matching: preserved for backwards compatibility with v4.
if (!this.matchPattern(decodedInput, endpointComponents[property])) {
return false;
}
}
}
}
return true;
}
/**
* Transforms relative urls to absolute urls
* @param url
* @returns
*/
private getAbsoluteUrl(url: string): string {
const link = this._document.createElement("a");
link.href = url;
return link.href;
}
/**
* Finds scopes from first matching endpoint with HTTP method that matches request
* @param protectedResourceMap Protected resource map
* @param endpointArray Array of resources that match request endpoint
* @param httpMethod Http method of the request
* @returns
*/
private matchScopesToEndpoint(
protectedResourceMap: Map<
string,
Array<string | ProtectedResourceScopes> | null
>,
endpointArray: string[],
httpMethod: string
): Array<string> | null {
const allMatchedScopes = [];
// Check each matched endpoint for matching HttpMethod and scopes
endpointArray.forEach((matchedEndpoint) => {
const scopesForEndpoint = [];
const methodAndScopesArray = protectedResourceMap.get(matchedEndpoint);
// Return if resource is unprotected
if (methodAndScopesArray === null) {
allMatchedScopes.push(null);
return;
}
methodAndScopesArray.forEach((entry) => {
// Entry is either array of scopes or ProtectedResourceScopes object
if (typeof entry === "string") {
scopesForEndpoint.push(entry);
} else {
// Ensure methods being compared are normalized
const normalizedRequestMethod = httpMethod.toLowerCase();
const normalizedResourceMethod = entry.httpMethod.toLowerCase();
// Method in protectedResourceMap matches request http method
if (normalizedResourceMethod === normalizedRequestMethod) {
// Validate if scopes comes null to unprotect the resource in a certain http method
if (entry.scopes === null) {
allMatchedScopes.push(null);
} else {
entry.scopes.forEach((scope) => {
scopesForEndpoint.push(scope);
});
}
}
}
});
// Only add to all scopes if scopes for endpoint and method is found
if (scopesForEndpoint.length > 0) {
allMatchedScopes.push(scopesForEndpoint);
}
});
if (allMatchedScopes.length > 0) {
if (allMatchedScopes.length > 1) {
this.authService
.getLogger()
.warning(
"Interceptor - More than 1 matching scopes for endpoint found.",
""
);
}
// Returns scopes for first matching endpoint
return allMatchedScopes[0];
}
return null;
}
/**
* Tests if a given string matches a given pattern, with support for wildcards and queries.
* @param pattern Wildcard pattern to string match. Supports "*" for wildcards and "?" for queries
* @param input String to match against
*/
private matchPattern(pattern: string, input: string): boolean {
/**
* Wildcard support: https://stackoverflow.com/a/3117248/4888559
* Queries: replaces "?" in string with escaped "\?" for regex test
*/
// eslint-disable-next-line security/detect-non-literal-regexp
const regex: RegExp = new RegExp(
pattern
.replace(/\\/g, "\\\\")
.replace(/\*/g, "[^ ]*")
.replace(/\?/g, "\\?")
);
return regex.test(input);
}
/**
* Tests if a given string matches a given pattern using stricter, anchored
* matching semantics.
*
* Differences from `matchPattern` (legacy):
* - All regex metacharacters (including `.` and `?`) are treated as literals.
* - The generated regex is anchored with `^` and `$` (full-string match).
* - `*` wildcard behaviour depends on the URL component:
* - `host`: `*` maps to `[^.]*` — matches any characters that do NOT
* include `.`, so wildcards stay within a single DNS label.
* - All other components: `*` matches any characters.
*
* @param pattern - The protectedResourceMap key pattern.
* @param input - The URL component value from the outgoing request.
* @param component - Which URL component is being matched.
* @returns `true` if the full input string matches the pattern.
*/
private matchPatternStrict(
pattern: string,
input: string,
component: "protocol" | "host" | "path" | "search" | "hash"
): boolean {
// Step 1: Escape all regex metacharacters so literals (including . and ?) match literally.
let regexBody = pattern.replace(/[.+^${}()|[\]\\*?]/g, "\\$&");
// Step 2: Replace escaped wildcards with component-aware regex equivalents.
if (component === "host") {
regexBody = regexBody.replace(/\\\*/g, "[^.]*");
} else {
// Path, protocol, search, hash: `*` matches any characters.
regexBody = regexBody.replace(/\\\*/g, ".*");
}
// Step 3: Anchor for full-string matching.
// eslint-disable-next-line security/detect-non-literal-regexp
const regex = new RegExp(`^${regexBody}$`);
return regex.test(input);
}
}