-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathStandardController.ts
2361 lines (2175 loc) · 87.8 KB
/
StandardController.ts
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { CryptoOps } from "../crypto/CryptoOps.js";
import {
InteractionRequiredAuthError,
AccountInfo,
Constants,
INetworkModule,
Logger,
CommonSilentFlowRequest,
ICrypto,
DEFAULT_CRYPTO_IMPLEMENTATION,
AuthError,
PerformanceEvents,
PerformanceCallbackFunction,
IPerformanceClient,
BaseAuthRequest,
PromptValue,
InProgressPerformanceEvent,
getRequestThumbprint,
invokeAsync,
createClientAuthError,
ClientAuthErrorCodes,
AccountFilter,
buildStaticAuthorityOptions,
InteractionRequiredAuthErrorCodes,
PkceCodes,
AccountEntityUtils,
} from "@azure/msal-common/browser";
import {
BrowserCacheManager,
DEFAULT_BROWSER_CACHE_MANAGER,
} from "../cache/BrowserCacheManager.js";
import * as AccountManager from "../cache/AccountManager.js";
import { BrowserConfiguration, CacheOptions } from "../config/Configuration.js";
import {
InteractionType,
ApiId,
BrowserCacheLocation,
WrapperSKU,
CacheLookupPolicy,
DEFAULT_REQUEST,
BrowserConstants,
iFrameRenewalPolicies,
INTERACTION_TYPE,
} from "../utils/BrowserConstants.js";
import * as BrowserUtils from "../utils/BrowserUtils.js";
import { RedirectRequest } from "../request/RedirectRequest.js";
import { PopupRequest } from "../request/PopupRequest.js";
import { SsoSilentRequest } from "../request/SsoSilentRequest.js";
import { EventCallbackFunction, EventError } from "../event/EventMessage.js";
import { EventType } from "../event/EventType.js";
import { EndSessionRequest } from "../request/EndSessionRequest.js";
import { EndSessionPopupRequest } from "../request/EndSessionPopupRequest.js";
import { INavigationClient } from "../navigation/INavigationClient.js";
import { EventHandler } from "../event/EventHandler.js";
import { PopupClient } from "../interaction_client/PopupClient.js";
import { RedirectClient } from "../interaction_client/RedirectClient.js";
import { SilentIframeClient } from "../interaction_client/SilentIframeClient.js";
import { SilentRefreshClient } from "../interaction_client/SilentRefreshClient.js";
import { TokenCache } from "../cache/TokenCache.js";
import { ITokenCache } from "../cache/ITokenCache.js";
import { NativeInteractionClient } from "../interaction_client/NativeInteractionClient.js";
import { NativeMessageHandler } from "../broker/nativeBroker/NativeMessageHandler.js";
import { SilentRequest } from "../request/SilentRequest.js";
import {
NativeAuthError,
isFatalNativeAuthError,
} from "../error/NativeAuthError.js";
import { SilentCacheClient } from "../interaction_client/SilentCacheClient.js";
import { SilentAuthCodeClient } from "../interaction_client/SilentAuthCodeClient.js";
import {
createBrowserAuthError,
BrowserAuthErrorCodes,
} from "../error/BrowserAuthError.js";
import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest.js";
import { NativeTokenRequest } from "../broker/nativeBroker/NativeRequest.js";
import { StandardOperatingContext } from "../operatingcontext/StandardOperatingContext.js";
import { BaseOperatingContext } from "../operatingcontext/BaseOperatingContext.js";
import { IController } from "./IController.js";
import { AuthenticationResult } from "../response/AuthenticationResult.js";
import { ClearCacheRequest } from "../request/ClearCacheRequest.js";
import { createNewGuid } from "../crypto/BrowserCrypto.js";
import { initializeSilentRequest } from "../request/RequestHelpers.js";
import { InitializeApplicationRequest } from "../request/InitializeApplicationRequest.js";
import { generatePkceCodes } from "../crypto/PkceGenerator.js";
function getAccountType(
account?: AccountInfo
): "AAD" | "MSA" | "B2C" | undefined {
const idTokenClaims = account?.idTokenClaims;
if (idTokenClaims?.tfp || idTokenClaims?.acr) {
return "B2C";
}
if (!idTokenClaims?.tid) {
return undefined;
} else if (idTokenClaims?.tid === "9188040d-6c67-4c5b-b112-36a304b66dad") {
return "MSA";
}
return "AAD";
}
function preflightCheck(
initialized: boolean,
performanceEvent: InProgressPerformanceEvent
) {
try {
BrowserUtils.preflightCheck(initialized);
} catch (e) {
performanceEvent.end({ success: false }, e);
throw e;
}
}
export class StandardController implements IController {
// OperatingContext
protected readonly operatingContext: StandardOperatingContext;
// Crypto interface implementation
protected readonly browserCrypto: ICrypto;
// Storage interface implementation
protected readonly browserStorage: BrowserCacheManager;
// Native Cache in memory storage implementation
protected readonly nativeInternalStorage: BrowserCacheManager;
// Network interface implementation
protected readonly networkClient: INetworkModule;
// Navigation interface implementation
protected navigationClient: INavigationClient;
// Input configuration by developer/user
protected readonly config: BrowserConfiguration;
// Token cache implementation
private tokenCache: TokenCache;
// Logger
protected logger: Logger;
// Flag to indicate if in browser environment
protected isBrowserEnvironment: boolean;
protected readonly eventHandler: EventHandler;
// Redirect Response Object
protected readonly redirectResponse: Map<
string,
Promise<AuthenticationResult | null>
>;
// Native Extension Provider
protected nativeExtensionProvider: NativeMessageHandler | undefined;
// Hybrid auth code responses
private hybridAuthCodeResponses: Map<string, Promise<AuthenticationResult>>;
// Performance telemetry client
protected readonly performanceClient: IPerformanceClient;
// Flag representing whether or not the initialize API has been called and completed
protected initialized: boolean;
// Active requests
private activeSilentTokenRequests: Map<
string,
Promise<AuthenticationResult>
>;
// Active Iframe request
private activeIframeRequest: [Promise<boolean>, string] | undefined;
private ssoSilentMeasurement?: InProgressPerformanceEvent;
private acquireTokenByCodeAsyncMeasurement?: InProgressPerformanceEvent;
private pkceCode: PkceCodes | undefined;
/**
* @constructor
* Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
*
* Important attributes in the Configuration object for auth are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
* - authority: the authority URL for your application.
* - redirect_uri: the uri of your application registered in the portal.
*
* In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
* It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
* Full B2C functionality will be available in this library in future versions.
*
* @param configuration Object for the MSAL PublicClientApplication instance
*/
constructor(operatingContext: StandardOperatingContext) {
this.operatingContext = operatingContext;
this.isBrowserEnvironment =
this.operatingContext.isBrowserEnvironment();
// Set the configuration.
this.config = operatingContext.getConfig();
this.initialized = false;
// Initialize logger
this.logger = this.operatingContext.getLogger();
// Initialize the network module class.
this.networkClient = this.config.system.networkClient;
// Initialize the navigation client class.
this.navigationClient = this.config.system.navigationClient;
// Initialize redirectResponse Map
this.redirectResponse = new Map();
// Initial hybrid spa map
this.hybridAuthCodeResponses = new Map();
// Initialize performance client
this.performanceClient = this.config.telemetry.client;
// Initialize the crypto class.
this.browserCrypto = this.isBrowserEnvironment
? new CryptoOps(this.logger, this.performanceClient)
: DEFAULT_CRYPTO_IMPLEMENTATION;
this.eventHandler = new EventHandler(this.logger);
// Initialize the browser storage class.
this.browserStorage = this.isBrowserEnvironment
? new BrowserCacheManager(
this.config.auth.clientId,
this.config.cache,
this.browserCrypto,
this.logger,
this.performanceClient,
this.eventHandler,
buildStaticAuthorityOptions(this.config.auth)
)
: DEFAULT_BROWSER_CACHE_MANAGER(
this.config.auth.clientId,
this.logger,
this.performanceClient,
this.eventHandler
);
// initialize in memory storage for native flows
const nativeCacheOptions: Required<CacheOptions> = {
cacheLocation: BrowserCacheLocation.MemoryStorage,
temporaryCacheLocation: BrowserCacheLocation.MemoryStorage,
claimsBasedCachingEnabled: false,
};
this.nativeInternalStorage = new BrowserCacheManager(
this.config.auth.clientId,
nativeCacheOptions,
this.browserCrypto,
this.logger,
this.performanceClient,
this.eventHandler
);
// Initialize the token cache
this.tokenCache = new TokenCache(
this.config,
this.browserStorage,
this.logger,
this.browserCrypto
);
this.activeSilentTokenRequests = new Map();
// Register listener functions
this.trackPageVisibility = this.trackPageVisibility.bind(this);
// Register listener functions
this.trackPageVisibilityWithMeasurement =
this.trackPageVisibilityWithMeasurement.bind(this);
}
static async createController(
operatingContext: BaseOperatingContext,
request?: InitializeApplicationRequest
): Promise<IController> {
const controller = new StandardController(operatingContext);
await controller.initialize(request);
return controller;
}
private trackPageVisibility(correlationId?: string): void {
if (!correlationId) {
return;
}
this.logger.info("Perf: Visibility change detected");
this.performanceClient.incrementFields(
{ visibilityChangeCount: 1 },
correlationId
);
}
/**
* Initializer function to perform async startup tasks such as connecting to WAM extension
* @param request {?InitializeApplicationRequest} correlation id
*/
async initialize(request?: InitializeApplicationRequest): Promise<void> {
this.logger.trace("initialize called");
if (this.initialized) {
this.logger.info(
"initialize has already been called, exiting early."
);
return;
}
if (!this.isBrowserEnvironment) {
this.logger.info("in non-browser environment, exiting early.");
this.initialized = true;
this.eventHandler.emitEvent(EventType.INITIALIZE_END);
return;
}
const initCorrelationId =
request?.correlationId || this.getRequestCorrelationId();
const allowPlatformBroker = this.config.system.allowPlatformBroker;
const initMeasurement = this.performanceClient.startMeasurement(
PerformanceEvents.InitializeClientApplication,
initCorrelationId
);
this.eventHandler.emitEvent(EventType.INITIALIZE_START);
await invokeAsync(
this.browserStorage.initialize.bind(this.browserStorage),
PerformanceEvents.InitializeCache,
this.logger,
this.performanceClient,
initCorrelationId
)(initCorrelationId);
if (allowPlatformBroker) {
try {
this.nativeExtensionProvider =
await NativeMessageHandler.createProvider(
this.logger,
this.config.system.nativeBrokerHandshakeTimeout,
this.performanceClient
);
} catch (e) {
this.logger.verbose(e as string);
}
}
if (!this.config.cache.claimsBasedCachingEnabled) {
this.logger.verbose(
"Claims-based caching is disabled. Clearing the previous cache with claims"
);
await invokeAsync(
this.browserStorage.clearTokensAndKeysWithClaims.bind(
this.browserStorage
),
PerformanceEvents.ClearTokensAndKeysWithClaims,
this.logger,
this.performanceClient,
initCorrelationId
)(this.performanceClient, initCorrelationId);
}
if (
this.config.cache.cacheLocation ===
BrowserCacheLocation.LocalStorage
) {
this.eventHandler.subscribeCrossTab();
}
this.config.system.asyncPopups &&
(await this.preGeneratePkceCodes(initCorrelationId));
this.initialized = true;
this.eventHandler.emitEvent(EventType.INITIALIZE_END);
initMeasurement.end({
allowPlatformBroker: allowPlatformBroker,
success: true,
});
}
// #region Redirect Flow
/**
* Event handler function which allows users to fire events after the PublicClientApplication object
* has loaded during redirect flows. This should be invoked on all page loads involved in redirect
* auth flows.
* @param hash Hash to process. Defaults to the current value of window.location.hash. Only needs to be provided explicitly if the response to be handled is not contained in the current value.
* @returns Token response or null. If the return value is null, then no auth redirect was detected.
*/
async handleRedirectPromise(
hash?: string
): Promise<AuthenticationResult | null> {
this.logger.verbose("handleRedirectPromise called");
// Block token acquisition before initialize has been called
BrowserUtils.blockAPICallsBeforeInitialize(this.initialized);
if (this.isBrowserEnvironment) {
/**
* Store the promise on the PublicClientApplication instance if this is the first invocation of handleRedirectPromise,
* otherwise return the promise from the first invocation. Prevents race conditions when handleRedirectPromise is called
* several times concurrently.
*/
const redirectResponseKey = hash || "";
let response = this.redirectResponse.get(redirectResponseKey);
if (typeof response === "undefined") {
response = this.handleRedirectPromiseInternal(hash);
this.redirectResponse.set(redirectResponseKey, response);
this.logger.verbose(
"handleRedirectPromise has been called for the first time, storing the promise"
);
} else {
this.logger.verbose(
"handleRedirectPromise has been called previously, returning the result from the first call"
);
}
return response;
}
this.logger.verbose(
"handleRedirectPromise returns null, not browser environment"
);
return null;
}
/**
* The internal details of handleRedirectPromise. This is separated out to a helper to allow handleRedirectPromise to memoize requests
* @param hash
* @returns
*/
private async handleRedirectPromiseInternal(
hash?: string
): Promise<AuthenticationResult | null> {
if (!this.browserStorage.isInteractionInProgress(true)) {
this.logger.info(
"handleRedirectPromise called but there is no interaction in progress, returning null."
);
return null;
}
const interactionType =
this.browserStorage.getInteractionInProgress()?.type;
if (interactionType === INTERACTION_TYPE.SIGNOUT) {
this.logger.verbose(
"handleRedirectPromise removing interaction_in_progress flag and returning null after sign-out"
);
this.browserStorage.setInteractionInProgress(false);
return Promise.resolve(null);
}
const loggedInAccounts = this.getAllAccounts();
const platformBrokerRequest: NativeTokenRequest | null =
this.browserStorage.getCachedNativeRequest();
const useNative =
platformBrokerRequest &&
NativeMessageHandler.isPlatformBrokerAvailable(
this.config,
this.logger,
this.nativeExtensionProvider
) &&
this.nativeExtensionProvider &&
!hash;
let rootMeasurement: InProgressPerformanceEvent;
this.eventHandler.emitEvent(
EventType.HANDLE_REDIRECT_START,
InteractionType.Redirect
);
let redirectResponse: Promise<AuthenticationResult | null>;
try {
if (useNative && this.nativeExtensionProvider) {
rootMeasurement = this.performanceClient.startMeasurement(
PerformanceEvents.AcquireTokenRedirect,
platformBrokerRequest?.correlationId || ""
);
this.logger.trace(
"handleRedirectPromise - acquiring token from native platform"
);
const nativeClient = new NativeInteractionClient(
this.config,
this.browserStorage,
this.browserCrypto,
this.logger,
this.eventHandler,
this.navigationClient,
ApiId.handleRedirectPromise,
this.performanceClient,
this.nativeExtensionProvider,
platformBrokerRequest.accountId,
this.nativeInternalStorage,
platformBrokerRequest.correlationId
);
redirectResponse = invokeAsync(
nativeClient.handleRedirectPromise.bind(nativeClient),
PerformanceEvents.HandleNativeRedirectPromiseMeasurement,
this.logger,
this.performanceClient,
rootMeasurement.event.correlationId
)(this.performanceClient, rootMeasurement.event.correlationId);
} else {
const [standardRequest, codeVerifier] =
this.browserStorage.getCachedRequest();
const correlationId = standardRequest.correlationId;
// Reset rootMeasurement now that we have correlationId
rootMeasurement = this.performanceClient.startMeasurement(
PerformanceEvents.AcquireTokenRedirect,
correlationId
);
this.logger.trace(
"handleRedirectPromise - acquiring token from web flow"
);
const redirectClient = this.createRedirectClient(correlationId);
redirectResponse = invokeAsync(
redirectClient.handleRedirectPromise.bind(redirectClient),
PerformanceEvents.HandleRedirectPromiseMeasurement,
this.logger,
this.performanceClient,
rootMeasurement.event.correlationId
)(hash, standardRequest, codeVerifier, rootMeasurement);
}
} catch (e) {
this.browserStorage.resetRequestCache();
throw e;
}
return redirectResponse
.then((result: AuthenticationResult | null) => {
if (result) {
this.browserStorage.resetRequestCache();
// Emit login event if number of accounts change
const isLoggingIn =
loggedInAccounts.length < this.getAllAccounts().length;
if (isLoggingIn) {
this.eventHandler.emitEvent(
EventType.LOGIN_SUCCESS,
InteractionType.Redirect,
result
);
this.logger.verbose(
"handleRedirectResponse returned result, login success"
);
} else {
this.eventHandler.emitEvent(
EventType.ACQUIRE_TOKEN_SUCCESS,
InteractionType.Redirect,
result
);
this.logger.verbose(
"handleRedirectResponse returned result, acquire token success"
);
}
rootMeasurement.end({
success: true,
accountType: getAccountType(result.account),
});
} else {
/*
* Instrument an event only if an error code is set. Otherwise, discard it when the redirect response
* is empty and the error code is missing.
*/
if (rootMeasurement.event.errorCode) {
rootMeasurement.end({ success: false });
} else {
rootMeasurement.discard();
}
}
this.eventHandler.emitEvent(
EventType.HANDLE_REDIRECT_END,
InteractionType.Redirect
);
return result;
})
.catch((e) => {
this.browserStorage.resetRequestCache();
const eventError = e as EventError;
// Emit login event if there is an account
if (loggedInAccounts.length > 0) {
this.eventHandler.emitEvent(
EventType.ACQUIRE_TOKEN_FAILURE,
InteractionType.Redirect,
null,
eventError
);
} else {
this.eventHandler.emitEvent(
EventType.LOGIN_FAILURE,
InteractionType.Redirect,
null,
eventError
);
}
this.eventHandler.emitEvent(
EventType.HANDLE_REDIRECT_END,
InteractionType.Redirect
);
rootMeasurement.end(
{
success: false,
},
eventError
);
throw e;
});
}
/**
* Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint. This function redirects
* the page, so any code that follows this function will not execute.
*
* IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
* browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
*
* @param request
*/
async acquireTokenRedirect(request: RedirectRequest): Promise<void> {
// Preflight request
const correlationId = this.getRequestCorrelationId(request);
this.logger.verbose("acquireTokenRedirect called", correlationId);
const atrMeasurement = this.performanceClient.startMeasurement(
PerformanceEvents.AcquireTokenPreRedirect,
correlationId
);
atrMeasurement.add({
accountType: getAccountType(request.account),
scenarioId: request.scenarioId,
});
const configOnRedirectNavigateCb = this.config.auth.onRedirectNavigate;
this.config.auth.onRedirectNavigate = (url: string) => {
const navigate =
typeof configOnRedirectNavigateCb === "function"
? configOnRedirectNavigateCb(url)
: undefined;
if (navigate !== false) {
atrMeasurement.end({ success: true });
} else {
atrMeasurement.discard();
}
return navigate;
};
// If logged in, emit acquire token events
const isLoggedIn = this.getAllAccounts().length > 0;
try {
BrowserUtils.redirectPreflightCheck(this.initialized, this.config);
this.browserStorage.setInteractionInProgress(
true,
INTERACTION_TYPE.SIGNIN
);
if (isLoggedIn) {
this.eventHandler.emitEvent(
EventType.ACQUIRE_TOKEN_START,
InteractionType.Redirect,
request
);
} else {
this.eventHandler.emitEvent(
EventType.LOGIN_START,
InteractionType.Redirect,
request
);
}
let result: Promise<void>;
if (
this.nativeExtensionProvider &&
this.canUsePlatformBroker(request)
) {
const nativeClient = new NativeInteractionClient(
this.config,
this.browserStorage,
this.browserCrypto,
this.logger,
this.eventHandler,
this.navigationClient,
ApiId.acquireTokenRedirect,
this.performanceClient,
this.nativeExtensionProvider,
this.getNativeAccountId(request),
this.nativeInternalStorage,
correlationId
);
result = nativeClient
.acquireTokenRedirect(request, atrMeasurement)
.catch((e: AuthError) => {
if (
e instanceof NativeAuthError &&
isFatalNativeAuthError(e)
) {
this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
const redirectClient =
this.createRedirectClient(correlationId);
return redirectClient.acquireToken(request);
} else if (e instanceof InteractionRequiredAuthError) {
this.logger.verbose(
"acquireTokenRedirect - Resolving interaction required error thrown by native broker by falling back to web flow"
);
const redirectClient =
this.createRedirectClient(correlationId);
return redirectClient.acquireToken(request);
}
throw e;
});
} else {
const redirectClient = this.createRedirectClient(correlationId);
result = redirectClient.acquireToken(request);
}
return await result;
} catch (e) {
this.browserStorage.resetRequestCache();
atrMeasurement.end({ success: false }, e);
if (isLoggedIn) {
this.eventHandler.emitEvent(
EventType.ACQUIRE_TOKEN_FAILURE,
InteractionType.Redirect,
null,
e as EventError
);
} else {
this.eventHandler.emitEvent(
EventType.LOGIN_FAILURE,
InteractionType.Redirect,
null,
e as EventError
);
}
throw e;
}
}
// #endregion
// #region Popup Flow
/**
* Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
*
* @param request
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
acquireTokenPopup(request: PopupRequest): Promise<AuthenticationResult> {
const correlationId = this.getRequestCorrelationId(request);
const atPopupMeasurement = this.performanceClient.startMeasurement(
PerformanceEvents.AcquireTokenPopup,
correlationId
);
atPopupMeasurement.add({
scenarioId: request.scenarioId,
accountType: getAccountType(request.account),
});
try {
this.logger.verbose("acquireTokenPopup called", correlationId);
preflightCheck(this.initialized, atPopupMeasurement);
this.browserStorage.setInteractionInProgress(
true,
INTERACTION_TYPE.SIGNIN
);
} catch (e) {
// Since this function is syncronous we need to reject
return Promise.reject(e);
}
// If logged in, emit acquire token events
const loggedInAccounts = this.getAllAccounts();
if (loggedInAccounts.length > 0) {
this.eventHandler.emitEvent(
EventType.ACQUIRE_TOKEN_START,
InteractionType.Popup,
request
);
} else {
this.eventHandler.emitEvent(
EventType.LOGIN_START,
InteractionType.Popup,
request
);
}
let result: Promise<AuthenticationResult>;
const pkce = this.getPreGeneratedPkceCodes(correlationId);
if (this.canUsePlatformBroker(request)) {
result = this.acquireTokenNative(
{
...request,
correlationId,
},
ApiId.acquireTokenPopup
)
.then((response) => {
atPopupMeasurement.end({
success: true,
isNativeBroker: true,
accountType: getAccountType(response.account),
});
return response;
})
.catch((e: AuthError) => {
if (
e instanceof NativeAuthError &&
isFatalNativeAuthError(e)
) {
this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
const popupClient =
this.createPopupClient(correlationId);
return popupClient.acquireToken(request, pkce);
} else if (e instanceof InteractionRequiredAuthError) {
this.logger.verbose(
"acquireTokenPopup - Resolving interaction required error thrown by native broker by falling back to web flow"
);
const popupClient =
this.createPopupClient(correlationId);
return popupClient.acquireToken(request, pkce);
}
throw e;
});
} else {
const popupClient = this.createPopupClient(correlationId);
result = popupClient.acquireToken(request, pkce);
}
return result
.then((result) => {
/*
* If logged in, emit acquire token events
*/
const isLoggingIn =
loggedInAccounts.length < this.getAllAccounts().length;
if (isLoggingIn) {
this.eventHandler.emitEvent(
EventType.LOGIN_SUCCESS,
InteractionType.Popup,
result
);
} else {
this.eventHandler.emitEvent(
EventType.ACQUIRE_TOKEN_SUCCESS,
InteractionType.Popup,
result
);
}
atPopupMeasurement.end({
success: true,
accessTokenSize: result.accessToken.length,
idTokenSize: result.idToken.length,
accountType: getAccountType(result.account),
});
return result;
})
.catch((e: Error) => {
if (loggedInAccounts.length > 0) {
this.eventHandler.emitEvent(
EventType.ACQUIRE_TOKEN_FAILURE,
InteractionType.Popup,
null,
e
);
} else {
this.eventHandler.emitEvent(
EventType.LOGIN_FAILURE,
InteractionType.Popup,
null,
e
);
}
atPopupMeasurement.end(
{
success: false,
},
e
);
// Since this function is syncronous we need to reject
return Promise.reject(e);
})
.finally(async () => {
this.browserStorage.setInteractionInProgress(false);
if (this.config.system.asyncPopups) {
await this.preGeneratePkceCodes(correlationId);
}
});
}
private trackPageVisibilityWithMeasurement(): void {
const measurement =
this.ssoSilentMeasurement ||
this.acquireTokenByCodeAsyncMeasurement;
if (!measurement) {
return;
}
this.logger.info(
"Perf: Visibility change detected in ",
measurement.event.name
);
measurement.increment({
visibilityChangeCount: 1,
});
}
// #endregion
// #region Silent Flow
/**
* This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
* - Any browser using a form of Intelligent Tracking Prevention
* - If there is not an established session with the service
*
* In these cases, the request must be done inside a popup or full frame redirect.
*
* For the cases where interaction is required, you cannot send a request with prompt=none.
*
* If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
* you session on the server still exists.
* @param request {@link SsoSilentRequest}
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
async ssoSilent(request: SsoSilentRequest): Promise<AuthenticationResult> {
const correlationId = this.getRequestCorrelationId(request);
const validRequest = {
...request,
// will be PromptValue.NONE or PromptValue.NO_SESSION
prompt: request.prompt,
correlationId: correlationId,
};
this.ssoSilentMeasurement = this.performanceClient.startMeasurement(
PerformanceEvents.SsoSilent,
correlationId
);
this.ssoSilentMeasurement?.add({
scenarioId: request.scenarioId,
accountType: getAccountType(request.account),
});
preflightCheck(this.initialized, this.ssoSilentMeasurement);
this.ssoSilentMeasurement?.increment({
visibilityChangeCount: 0,
});
document.addEventListener(
"visibilitychange",
this.trackPageVisibilityWithMeasurement
);
this.logger.verbose("ssoSilent called", correlationId);
this.eventHandler.emitEvent(
EventType.SSO_SILENT_START,
InteractionType.Silent,
validRequest
);
let result: Promise<AuthenticationResult>;
if (this.canUsePlatformBroker(validRequest)) {
result = this.acquireTokenNative(
validRequest,
ApiId.ssoSilent
).catch((e: AuthError) => {
// If native token acquisition fails for availability reasons fallback to standard flow
if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
const silentIframeClient = this.createSilentIframeClient(
validRequest.correlationId
);
return silentIframeClient.acquireToken(validRequest);
}
throw e;
});
} else {
const silentIframeClient = this.createSilentIframeClient(
validRequest.correlationId
);
result = silentIframeClient.acquireToken(validRequest);
}
return result
.then((response) => {