@azure/msal-browser 3.20.0 → 3.22.0

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.
Files changed (187) hide show
  1. package/dist/app/IPublicClientApplication.d.ts +53 -53
  2. package/dist/app/IPublicClientApplication.mjs +105 -105
  3. package/dist/app/PublicClientApplication.d.ts +293 -293
  4. package/dist/app/PublicClientApplication.mjs +364 -364
  5. package/dist/app/PublicClientNext.d.ts +276 -276
  6. package/dist/app/PublicClientNext.mjs +354 -354
  7. package/dist/broker/nativeBroker/NativeMessageHandler.d.ts +62 -62
  8. package/dist/broker/nativeBroker/NativeMessageHandler.mjs +254 -254
  9. package/dist/broker/nativeBroker/NativeRequest.d.ts +45 -45
  10. package/dist/broker/nativeBroker/NativeResponse.d.ts +48 -48
  11. package/dist/broker/nativeBroker/NativeStatusCodes.d.ts +7 -7
  12. package/dist/broker/nativeBroker/NativeStatusCodes.mjs +11 -11
  13. package/dist/cache/AccountManager.d.ts +48 -48
  14. package/dist/cache/AccountManager.mjs +126 -126
  15. package/dist/cache/AsyncMemoryStorage.d.ts +50 -50
  16. package/dist/cache/AsyncMemoryStorage.mjs +131 -131
  17. package/dist/cache/BrowserCacheManager.d.ts +385 -385
  18. package/dist/cache/BrowserCacheManager.mjs +1294 -1294
  19. package/dist/cache/BrowserStorage.d.ts +11 -11
  20. package/dist/cache/BrowserStorage.mjs +32 -32
  21. package/dist/cache/DatabaseStorage.d.ts +56 -56
  22. package/dist/cache/DatabaseStorage.mjs +200 -200
  23. package/dist/cache/IAsyncStorage.d.ts +27 -27
  24. package/dist/cache/ITokenCache.d.ts +11 -11
  25. package/dist/cache/IWindowStorage.d.ts +27 -27
  26. package/dist/cache/MemoryStorage.d.ts +11 -11
  27. package/dist/cache/MemoryStorage.mjs +31 -31
  28. package/dist/cache/TokenCache.d.ts +77 -77
  29. package/dist/cache/TokenCache.mjs +195 -195
  30. package/dist/config/Configuration.d.ts +213 -208
  31. package/dist/config/Configuration.d.ts.map +1 -1
  32. package/dist/config/Configuration.mjs +128 -128
  33. package/dist/config/Configuration.mjs.map +1 -1
  34. package/dist/controllers/ControllerFactory.d.ts +5 -5
  35. package/dist/controllers/ControllerFactory.mjs +25 -25
  36. package/dist/controllers/IController.d.ts +60 -60
  37. package/dist/controllers/NestedAppAuthController.d.ts +202 -202
  38. package/dist/controllers/NestedAppAuthController.mjs +473 -473
  39. package/dist/controllers/StandardController.d.ts +405 -405
  40. package/dist/controllers/StandardController.d.ts.map +1 -1
  41. package/dist/controllers/StandardController.mjs +1334 -1316
  42. package/dist/controllers/StandardController.mjs.map +1 -1
  43. package/dist/controllers/UnknownOperatingContextController.d.ts +86 -86
  44. package/dist/controllers/UnknownOperatingContextController.mjs +256 -256
  45. package/dist/crypto/BrowserCrypto.d.ts +52 -52
  46. package/dist/crypto/BrowserCrypto.mjs +151 -151
  47. package/dist/crypto/CryptoOps.d.ts +74 -74
  48. package/dist/crypto/CryptoOps.mjs +176 -176
  49. package/dist/crypto/PkceGenerator.d.ts +8 -8
  50. package/dist/crypto/PkceGenerator.mjs +54 -54
  51. package/dist/crypto/SignedHttpRequest.d.ts +30 -30
  52. package/dist/crypto/SignedHttpRequest.mjs +39 -39
  53. package/dist/encode/Base64Decode.d.ts +9 -9
  54. package/dist/encode/Base64Decode.mjs +36 -36
  55. package/dist/encode/Base64Encode.d.ts +19 -19
  56. package/dist/encode/Base64Encode.mjs +43 -43
  57. package/dist/error/BrowserAuthError.d.ts +255 -255
  58. package/dist/error/BrowserAuthError.mjs +263 -263
  59. package/dist/error/BrowserAuthErrorCodes.d.ts +46 -46
  60. package/dist/error/BrowserAuthErrorCodes.mjs +50 -50
  61. package/dist/error/BrowserConfigurationAuthError.d.ts +33 -33
  62. package/dist/error/BrowserConfigurationAuthError.mjs +40 -40
  63. package/dist/error/BrowserConfigurationAuthError.mjs.map +1 -1
  64. package/dist/error/BrowserConfigurationAuthErrorCodes.d.ts +3 -3
  65. package/dist/error/BrowserConfigurationAuthErrorCodes.mjs +7 -7
  66. package/dist/error/NativeAuthError.d.ts +29 -29
  67. package/dist/error/NativeAuthError.mjs +60 -60
  68. package/dist/error/NativeAuthErrorCodes.d.ts +2 -2
  69. package/dist/error/NativeAuthErrorCodes.mjs +6 -6
  70. package/dist/error/NestedAppAuthError.d.ts +14 -14
  71. package/dist/error/NestedAppAuthError.mjs +23 -23
  72. package/dist/event/EventHandler.d.ts +41 -41
  73. package/dist/event/EventHandler.mjs +125 -125
  74. package/dist/event/EventMessage.d.ts +25 -25
  75. package/dist/event/EventMessage.mjs +68 -68
  76. package/dist/event/EventType.d.ts +29 -29
  77. package/dist/event/EventType.mjs +32 -32
  78. package/dist/index.d.ts +40 -40
  79. package/dist/index.mjs +1 -1
  80. package/dist/interaction_client/BaseInteractionClient.d.ts +50 -50
  81. package/dist/interaction_client/BaseInteractionClient.mjs +106 -106
  82. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.d.ts +4 -4
  83. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.mjs +10 -10
  84. package/dist/interaction_client/NativeInteractionClient.d.ts +151 -151
  85. package/dist/interaction_client/NativeInteractionClient.mjs +621 -621
  86. package/dist/interaction_client/PopupClient.d.ts +105 -105
  87. package/dist/interaction_client/PopupClient.d.ts.map +1 -1
  88. package/dist/interaction_client/PopupClient.mjs +433 -433
  89. package/dist/interaction_client/PopupClient.mjs.map +1 -1
  90. package/dist/interaction_client/RedirectClient.d.ts +50 -50
  91. package/dist/interaction_client/RedirectClient.d.ts.map +1 -1
  92. package/dist/interaction_client/RedirectClient.mjs +315 -314
  93. package/dist/interaction_client/RedirectClient.mjs.map +1 -1
  94. package/dist/interaction_client/SilentAuthCodeClient.d.ts +23 -23
  95. package/dist/interaction_client/SilentAuthCodeClient.mjs +57 -57
  96. package/dist/interaction_client/SilentCacheClient.d.ts +16 -16
  97. package/dist/interaction_client/SilentCacheClient.mjs +42 -42
  98. package/dist/interaction_client/SilentIframeClient.d.ts +32 -32
  99. package/dist/interaction_client/SilentIframeClient.d.ts.map +1 -1
  100. package/dist/interaction_client/SilentIframeClient.mjs +110 -100
  101. package/dist/interaction_client/SilentIframeClient.mjs.map +1 -1
  102. package/dist/interaction_client/SilentRefreshClient.d.ts +20 -20
  103. package/dist/interaction_client/SilentRefreshClient.mjs +47 -47
  104. package/dist/interaction_client/StandardInteractionClient.d.ts +48 -48
  105. package/dist/interaction_client/StandardInteractionClient.mjs +199 -199
  106. package/dist/interaction_handler/InteractionHandler.d.ts +33 -33
  107. package/dist/interaction_handler/InteractionHandler.mjs +93 -93
  108. package/dist/interaction_handler/RedirectHandler.d.ts +32 -32
  109. package/dist/interaction_handler/RedirectHandler.mjs +134 -134
  110. package/dist/interaction_handler/SilentHandler.d.ts +13 -13
  111. package/dist/interaction_handler/SilentHandler.mjs +134 -134
  112. package/dist/naa/AccountInfo.d.ts +11 -11
  113. package/dist/naa/AuthBridge.d.ts +8 -8
  114. package/dist/naa/AuthResult.d.ts +6 -6
  115. package/dist/naa/BridgeAccountContext.d.ts +12 -12
  116. package/dist/naa/BridgeCapabilities.d.ts +3 -3
  117. package/dist/naa/BridgeError.d.ts +9 -9
  118. package/dist/naa/BridgeError.mjs +7 -7
  119. package/dist/naa/BridgeProxy.d.ts +67 -67
  120. package/dist/naa/BridgeProxy.mjs +148 -148
  121. package/dist/naa/BridgeRequest.d.ts +7 -7
  122. package/dist/naa/BridgeRequestEnvelope.d.ts +12 -12
  123. package/dist/naa/BridgeResponseEnvelope.d.ts +13 -13
  124. package/dist/naa/BridgeStatusCode.d.ts +11 -11
  125. package/dist/naa/BridgeStatusCode.mjs +14 -14
  126. package/dist/naa/IBridgeProxy.d.ts +10 -10
  127. package/dist/naa/InitContext.d.ts +8 -8
  128. package/dist/naa/TokenRequest.d.ts +18 -18
  129. package/dist/naa/TokenResponse.d.ts +13 -13
  130. package/dist/naa/mapping/NestedAppAuthAdapter.d.ts +35 -35
  131. package/dist/naa/mapping/NestedAppAuthAdapter.mjs +179 -179
  132. package/dist/navigation/INavigationClient.d.ts +16 -16
  133. package/dist/navigation/NavigationClient.d.ts +22 -22
  134. package/dist/navigation/NavigationClient.mjs +40 -40
  135. package/dist/navigation/NavigationOptions.d.ts +12 -12
  136. package/dist/network/FetchClient.d.ts +26 -26
  137. package/dist/network/FetchClient.mjs +99 -99
  138. package/dist/operatingcontext/BaseOperatingContext.d.ts +41 -41
  139. package/dist/operatingcontext/BaseOperatingContext.mjs +94 -94
  140. package/dist/operatingcontext/NestedAppOperatingContext.d.ts +34 -34
  141. package/dist/operatingcontext/NestedAppOperatingContext.mjs +71 -71
  142. package/dist/operatingcontext/StandardOperatingContext.d.ts +25 -25
  143. package/dist/operatingcontext/StandardOperatingContext.mjs +43 -43
  144. package/dist/operatingcontext/UnknownOperatingContext.d.ts +25 -25
  145. package/dist/operatingcontext/UnknownOperatingContext.mjs +42 -42
  146. package/dist/packageMetadata.d.ts +2 -2
  147. package/dist/packageMetadata.mjs +4 -4
  148. package/dist/request/AuthorizationCodeRequest.d.ts +8 -8
  149. package/dist/request/AuthorizationUrlRequest.d.ts +8 -8
  150. package/dist/request/ClearCacheRequest.d.ts +10 -10
  151. package/dist/request/EndSessionPopupRequest.d.ts +18 -18
  152. package/dist/request/EndSessionRequest.d.ts +15 -15
  153. package/dist/request/InitializeApplicationRequest.d.ts +8 -8
  154. package/dist/request/PopupRequest.d.ts +34 -34
  155. package/dist/request/PopupWindowAttributes.d.ts +15 -15
  156. package/dist/request/RedirectRequest.d.ts +40 -35
  157. package/dist/request/RedirectRequest.d.ts.map +1 -1
  158. package/dist/request/RequestHelpers.d.ts +13 -13
  159. package/dist/request/RequestHelpers.mjs +53 -53
  160. package/dist/request/SilentRequest.d.ts +33 -33
  161. package/dist/request/SsoSilentRequest.d.ts +29 -29
  162. package/dist/response/AuthenticationResult.d.ts +4 -4
  163. package/dist/response/ResponseHandler.d.ts +7 -7
  164. package/dist/response/ResponseHandler.mjs +36 -36
  165. package/dist/telemetry/BrowserPerformanceClient.d.ts +34 -34
  166. package/dist/telemetry/BrowserPerformanceClient.mjs +162 -162
  167. package/dist/telemetry/BrowserPerformanceMeasurement.d.ts +21 -21
  168. package/dist/telemetry/BrowserPerformanceMeasurement.mjs +92 -92
  169. package/dist/utils/BrowserConstants.d.ts +180 -180
  170. package/dist/utils/BrowserConstants.mjs +212 -212
  171. package/dist/utils/BrowserProtocolUtils.d.ts +11 -11
  172. package/dist/utils/BrowserProtocolUtils.mjs +21 -21
  173. package/dist/utils/BrowserUtils.d.ts +75 -75
  174. package/dist/utils/BrowserUtils.mjs +157 -157
  175. package/lib/msal-browser.cjs +18884 -18855
  176. package/lib/msal-browser.cjs.map +1 -1
  177. package/lib/msal-browser.js +18884 -18855
  178. package/lib/msal-browser.js.map +1 -1
  179. package/lib/msal-browser.min.js +59 -59
  180. package/package.json +2 -2
  181. package/src/config/Configuration.ts +9 -1
  182. package/src/controllers/StandardController.ts +30 -12
  183. package/src/interaction_client/PopupClient.ts +1 -0
  184. package/src/interaction_client/RedirectClient.ts +4 -1
  185. package/src/interaction_client/SilentIframeClient.ts +40 -3
  186. package/src/packageMetadata.ts +1 -1
  187. package/src/request/RedirectRequest.ts +5 -0
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-browser v3.20.0 2024-07-23 */
1
+ /*! @azure/msal-browser v3.22.0 2024-08-28 */
2
2
  'use strict';
3
3
  import { CryptoOps } from '../crypto/CryptoOps.mjs';
4
4
  import { DEFAULT_CRYPTO_IMPLEMENTATION, buildStaticAuthorityOptions, PerformanceEvents, invokeAsync, InteractionRequiredAuthError, createClientAuthError, ClientAuthErrorCodes, AccountEntity, PromptValue, Constants, InteractionRequiredAuthErrorCodes } from '@azure/msal-common';
@@ -23,1321 +23,1339 @@ import { createNewGuid } from '../crypto/BrowserCrypto.mjs';
23
23
  import { initializeSilentRequest } from '../request/RequestHelpers.mjs';
24
24
  import { spaCodeAndNativeAccountIdPresent, unableToAcquireTokenFromNativePlatform, authCodeOrNativeAccountIdRequired, nativeConnectionNotEstablished, noAccountError } from '../error/BrowserAuthErrorCodes.mjs';
25
25
 
26
- /*
27
- * Copyright (c) Microsoft Corporation. All rights reserved.
28
- * Licensed under the MIT License.
29
- */
30
- function getAccountType(account) {
31
- const idTokenClaims = account?.idTokenClaims;
32
- if (idTokenClaims?.tfp || idTokenClaims?.acr) {
33
- return "B2C";
34
- }
35
- if (!idTokenClaims?.tid) {
36
- return undefined;
37
- }
38
- else if (idTokenClaims?.tid === "9188040d-6c67-4c5b-b112-36a304b66dad") {
39
- return "MSA";
40
- }
41
- return "AAD";
42
- }
43
- function preflightCheck(initialized, performanceEvent) {
44
- try {
45
- preflightCheck$1(initialized);
46
- }
47
- catch (e) {
48
- performanceEvent.end({ success: false }, e);
49
- throw e;
50
- }
51
- }
52
- class StandardController {
53
- /**
54
- * @constructor
55
- * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
56
- *
57
- * Important attributes in the Configuration object for auth are:
58
- * - 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
59
- * - authority: the authority URL for your application.
60
- * - redirect_uri: the uri of your application registered in the portal.
61
- *
62
- * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
63
- * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
64
- * 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).
65
- * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
66
- * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
67
- * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
68
- *
69
- * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
70
- * Full B2C functionality will be available in this library in future versions.
71
- *
72
- * @param configuration Object for the MSAL PublicClientApplication instance
73
- */
74
- constructor(operatingContext) {
75
- this.operatingContext = operatingContext;
76
- this.isBrowserEnvironment =
77
- this.operatingContext.isBrowserEnvironment();
78
- // Set the configuration.
79
- this.config = operatingContext.getConfig();
80
- this.initialized = false;
81
- // Initialize logger
82
- this.logger = this.operatingContext.getLogger();
83
- // Initialize the network module class.
84
- this.networkClient = this.config.system.networkClient;
85
- // Initialize the navigation client class.
86
- this.navigationClient = this.config.system.navigationClient;
87
- // Initialize redirectResponse Map
88
- this.redirectResponse = new Map();
89
- // Initial hybrid spa map
90
- this.hybridAuthCodeResponses = new Map();
91
- // Initialize performance client
92
- this.performanceClient = this.config.telemetry.client;
93
- // Initialize the crypto class.
94
- this.browserCrypto = this.isBrowserEnvironment
95
- ? new CryptoOps(this.logger, this.performanceClient)
96
- : DEFAULT_CRYPTO_IMPLEMENTATION;
97
- this.eventHandler = new EventHandler(this.logger, this.browserCrypto);
98
- // Initialize the browser storage class.
99
- this.browserStorage = this.isBrowserEnvironment
100
- ? new BrowserCacheManager(this.config.auth.clientId, this.config.cache, this.browserCrypto, this.logger, buildStaticAuthorityOptions(this.config.auth), this.performanceClient)
101
- : DEFAULT_BROWSER_CACHE_MANAGER(this.config.auth.clientId, this.logger);
102
- // initialize in memory storage for native flows
103
- const nativeCacheOptions = {
104
- cacheLocation: BrowserCacheLocation.MemoryStorage,
105
- temporaryCacheLocation: BrowserCacheLocation.MemoryStorage,
106
- storeAuthStateInCookie: false,
107
- secureCookies: false,
108
- cacheMigrationEnabled: false,
109
- claimsBasedCachingEnabled: false,
110
- };
111
- this.nativeInternalStorage = new BrowserCacheManager(this.config.auth.clientId, nativeCacheOptions, this.browserCrypto, this.logger, undefined, this.performanceClient);
112
- // Initialize the token cache
113
- this.tokenCache = new TokenCache(this.config, this.browserStorage, this.logger, this.browserCrypto);
114
- this.activeSilentTokenRequests = new Map();
115
- // Register listener functions
116
- this.trackPageVisibility = this.trackPageVisibility.bind(this);
117
- // Register listener functions
118
- this.trackPageVisibilityWithMeasurement =
119
- this.trackPageVisibilityWithMeasurement.bind(this);
120
- }
121
- static async createController(operatingContext, request) {
122
- const controller = new StandardController(operatingContext);
123
- await controller.initialize(request);
124
- return controller;
125
- }
126
- trackPageVisibility(correlationId) {
127
- if (!correlationId) {
128
- return;
129
- }
130
- this.logger.info("Perf: Visibility change detected");
131
- this.performanceClient.incrementFields({ visibilityChangeCount: 1 }, correlationId);
132
- }
133
- /**
134
- * Initializer function to perform async startup tasks such as connecting to WAM extension
135
- * @param request {?InitializeApplicationRequest} correlation id
136
- */
137
- async initialize(request) {
138
- this.logger.trace("initialize called");
139
- if (this.initialized) {
140
- this.logger.info("initialize has already been called, exiting early.");
141
- return;
142
- }
143
- const initCorrelationId = request?.correlationId || this.getRequestCorrelationId();
144
- const allowNativeBroker = this.config.system.allowNativeBroker;
145
- const initMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.InitializeClientApplication, initCorrelationId);
146
- this.eventHandler.emitEvent(EventType.INITIALIZE_START);
147
- if (allowNativeBroker) {
148
- try {
149
- this.nativeExtensionProvider =
150
- await NativeMessageHandler.createProvider(this.logger, this.config.system.nativeBrokerHandshakeTimeout, this.performanceClient);
151
- }
152
- catch (e) {
153
- this.logger.verbose(e);
154
- }
155
- }
156
- if (!this.config.cache.claimsBasedCachingEnabled) {
157
- this.logger.verbose("Claims-based caching is disabled. Clearing the previous cache with claims");
158
- await invokeAsync(this.browserStorage.clearTokensAndKeysWithClaims.bind(this.browserStorage), PerformanceEvents.ClearTokensAndKeysWithClaims, this.logger, this.performanceClient, initCorrelationId)(this.performanceClient, initCorrelationId);
159
- }
160
- this.initialized = true;
161
- this.eventHandler.emitEvent(EventType.INITIALIZE_END);
162
- initMeasurement.end({ allowNativeBroker, success: true });
163
- }
164
- // #region Redirect Flow
165
- /**
166
- * Event handler function which allows users to fire events after the PublicClientApplication object
167
- * has loaded during redirect flows. This should be invoked on all page loads involved in redirect
168
- * auth flows.
169
- * @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.
170
- * @returns Token response or null. If the return value is null, then no auth redirect was detected.
171
- */
172
- async handleRedirectPromise(hash) {
173
- this.logger.verbose("handleRedirectPromise called");
174
- // Block token acquisition before initialize has been called
175
- blockAPICallsBeforeInitialize(this.initialized);
176
- if (this.isBrowserEnvironment) {
177
- /**
178
- * Store the promise on the PublicClientApplication instance if this is the first invocation of handleRedirectPromise,
179
- * otherwise return the promise from the first invocation. Prevents race conditions when handleRedirectPromise is called
180
- * several times concurrently.
181
- */
182
- const redirectResponseKey = hash || "";
183
- let response = this.redirectResponse.get(redirectResponseKey);
184
- if (typeof response === "undefined") {
185
- response = this.handleRedirectPromiseInternal(hash);
186
- this.redirectResponse.set(redirectResponseKey, response);
187
- this.logger.verbose("handleRedirectPromise has been called for the first time, storing the promise");
188
- }
189
- else {
190
- this.logger.verbose("handleRedirectPromise has been called previously, returning the result from the first call");
191
- }
192
- return response;
193
- }
194
- this.logger.verbose("handleRedirectPromise returns null, not browser environment");
195
- return null;
196
- }
197
- /**
198
- * The internal details of handleRedirectPromise. This is separated out to a helper to allow handleRedirectPromise to memoize requests
199
- * @param hash
200
- * @returns
201
- */
202
- async handleRedirectPromiseInternal(hash) {
203
- const loggedInAccounts = this.getAllAccounts();
204
- const request = this.browserStorage.getCachedNativeRequest();
205
- const useNative = request &&
206
- NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeExtensionProvider) &&
207
- this.nativeExtensionProvider &&
208
- !hash;
209
- const correlationId = useNative
210
- ? request?.correlationId
211
- : this.browserStorage.getTemporaryCache(TemporaryCacheKeys.CORRELATION_ID, true) || "";
212
- const rootMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenRedirect, correlationId);
213
- this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, InteractionType.Redirect);
214
- let redirectResponse;
215
- if (useNative && this.nativeExtensionProvider) {
216
- this.logger.trace("handleRedirectPromise - acquiring token from native platform");
217
- const nativeClient = new NativeInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.handleRedirectPromise, this.performanceClient, this.nativeExtensionProvider, request.accountId, this.nativeInternalStorage, request.correlationId);
218
- redirectResponse = invokeAsync(nativeClient.handleRedirectPromise.bind(nativeClient), PerformanceEvents.HandleNativeRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)(this.performanceClient, rootMeasurement.event.correlationId);
219
- }
220
- else {
221
- this.logger.trace("handleRedirectPromise - acquiring token from web flow");
222
- const redirectClient = this.createRedirectClient(correlationId);
223
- redirectResponse = invokeAsync(redirectClient.handleRedirectPromise.bind(redirectClient), PerformanceEvents.HandleRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)(hash, rootMeasurement);
224
- }
225
- return redirectResponse
226
- .then((result) => {
227
- if (result) {
228
- // Emit login event if number of accounts change
229
- const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
230
- if (isLoggingIn) {
231
- this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, InteractionType.Redirect, result);
232
- this.logger.verbose("handleRedirectResponse returned result, login success");
233
- }
234
- else {
235
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, InteractionType.Redirect, result);
236
- this.logger.verbose("handleRedirectResponse returned result, acquire token success");
237
- }
238
- rootMeasurement.end({
239
- success: true,
240
- accountType: getAccountType(result.account),
241
- });
242
- }
243
- else {
244
- /*
245
- * Instrument an event only if an error code is set. Otherwise, discard it when the redirect response
246
- * is empty and the error code is missing.
247
- */
248
- if (rootMeasurement.event.errorCode) {
249
- rootMeasurement.end({ success: false });
250
- }
251
- else {
252
- rootMeasurement.discard();
253
- }
254
- }
255
- this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, InteractionType.Redirect);
256
- return result;
257
- })
258
- .catch((e) => {
259
- const eventError = e;
260
- // Emit login event if there is an account
261
- if (loggedInAccounts.length > 0) {
262
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, InteractionType.Redirect, null, eventError);
263
- }
264
- else {
265
- this.eventHandler.emitEvent(EventType.LOGIN_FAILURE, InteractionType.Redirect, null, eventError);
266
- }
267
- this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, InteractionType.Redirect);
268
- rootMeasurement.end({
269
- success: false,
270
- }, eventError);
271
- throw e;
272
- });
273
- }
274
- /**
275
- * 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
276
- * the page, so any code that follows this function will not execute.
277
- *
278
- * 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
279
- * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
280
- *
281
- * @param request
282
- */
283
- async acquireTokenRedirect(request) {
284
- // Preflight request
285
- const correlationId = this.getRequestCorrelationId(request);
286
- this.logger.verbose("acquireTokenRedirect called", correlationId);
287
- const atrMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenPreRedirect, correlationId);
288
- atrMeasurement.add({
289
- accountType: getAccountType(request.account),
290
- scenarioId: request.scenarioId,
291
- });
292
- const onRedirectNavigateCb = request.onRedirectNavigate;
293
- request.onRedirectNavigate = (url) => {
294
- const navigate = typeof onRedirectNavigateCb === "function"
295
- ? onRedirectNavigateCb(url)
296
- : undefined;
297
- if (navigate !== false) {
298
- atrMeasurement.end({ success: true });
299
- }
300
- else {
301
- atrMeasurement.discard();
302
- }
303
- return navigate;
304
- };
305
- // If logged in, emit acquire token events
306
- const isLoggedIn = this.getAllAccounts().length > 0;
307
- try {
308
- redirectPreflightCheck(this.initialized, this.config);
309
- this.browserStorage.setInteractionInProgress(true);
310
- if (isLoggedIn) {
311
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, InteractionType.Redirect, request);
312
- }
313
- else {
314
- this.eventHandler.emitEvent(EventType.LOGIN_START, InteractionType.Redirect, request);
315
- }
316
- let result;
317
- if (this.nativeExtensionProvider && this.canUseNative(request)) {
318
- 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);
319
- result = nativeClient
320
- .acquireTokenRedirect(request, atrMeasurement)
321
- .catch((e) => {
322
- if (e instanceof NativeAuthError &&
323
- isFatalNativeAuthError(e)) {
324
- this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
325
- const redirectClient = this.createRedirectClient(correlationId);
326
- return redirectClient.acquireToken(request);
327
- }
328
- else if (e instanceof InteractionRequiredAuthError) {
329
- this.logger.verbose("acquireTokenRedirect - Resolving interaction required error thrown by native broker by falling back to web flow");
330
- const redirectClient = this.createRedirectClient(correlationId);
331
- return redirectClient.acquireToken(request);
332
- }
333
- this.browserStorage.setInteractionInProgress(false);
334
- throw e;
335
- });
336
- }
337
- else {
338
- const redirectClient = this.createRedirectClient(correlationId);
339
- result = redirectClient.acquireToken(request);
340
- }
341
- return await result;
342
- }
343
- catch (e) {
344
- atrMeasurement.end({ success: false }, e);
345
- if (isLoggedIn) {
346
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, InteractionType.Redirect, null, e);
347
- }
348
- else {
349
- this.eventHandler.emitEvent(EventType.LOGIN_FAILURE, InteractionType.Redirect, null, e);
350
- }
351
- throw e;
352
- }
353
- }
354
- // #endregion
355
- // #region Popup Flow
356
- /**
357
- * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
358
- *
359
- * @param request
360
- *
361
- * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
362
- */
363
- acquireTokenPopup(request) {
364
- const correlationId = this.getRequestCorrelationId(request);
365
- const atPopupMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenPopup, correlationId);
366
- atPopupMeasurement.add({
367
- scenarioId: request.scenarioId,
368
- accountType: getAccountType(request.account),
369
- });
370
- try {
371
- this.logger.verbose("acquireTokenPopup called", correlationId);
372
- preflightCheck(this.initialized, atPopupMeasurement);
373
- this.browserStorage.setInteractionInProgress(true);
374
- }
375
- catch (e) {
376
- // Since this function is syncronous we need to reject
377
- return Promise.reject(e);
378
- }
379
- // If logged in, emit acquire token events
380
- const loggedInAccounts = this.getAllAccounts();
381
- if (loggedInAccounts.length > 0) {
382
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, InteractionType.Popup, request);
383
- }
384
- else {
385
- this.eventHandler.emitEvent(EventType.LOGIN_START, InteractionType.Popup, request);
386
- }
387
- let result;
388
- if (this.canUseNative(request)) {
389
- result = this.acquireTokenNative({
390
- ...request,
391
- correlationId,
392
- }, ApiId.acquireTokenPopup)
393
- .then((response) => {
394
- this.browserStorage.setInteractionInProgress(false);
395
- atPopupMeasurement.end({
396
- success: true,
397
- isNativeBroker: true,
398
- requestId: response.requestId,
399
- accountType: getAccountType(response.account),
400
- });
401
- return response;
402
- })
403
- .catch((e) => {
404
- if (e instanceof NativeAuthError &&
405
- isFatalNativeAuthError(e)) {
406
- this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
407
- const popupClient = this.createPopupClient(correlationId);
408
- return popupClient.acquireToken(request);
409
- }
410
- else if (e instanceof InteractionRequiredAuthError) {
411
- this.logger.verbose("acquireTokenPopup - Resolving interaction required error thrown by native broker by falling back to web flow");
412
- const popupClient = this.createPopupClient(correlationId);
413
- return popupClient.acquireToken(request);
414
- }
415
- this.browserStorage.setInteractionInProgress(false);
416
- throw e;
417
- });
418
- }
419
- else {
420
- const popupClient = this.createPopupClient(correlationId);
421
- result = popupClient.acquireToken(request);
422
- }
423
- return result
424
- .then((result) => {
425
- /*
426
- * If logged in, emit acquire token events
427
- */
428
- const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
429
- if (isLoggingIn) {
430
- this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, InteractionType.Popup, result);
431
- }
432
- else {
433
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, InteractionType.Popup, result);
434
- }
435
- atPopupMeasurement.end({
436
- success: true,
437
- requestId: result.requestId,
438
- accessTokenSize: result.accessToken.length,
439
- idTokenSize: result.idToken.length,
440
- accountType: getAccountType(result.account),
441
- });
442
- return result;
443
- })
444
- .catch((e) => {
445
- if (loggedInAccounts.length > 0) {
446
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, InteractionType.Popup, null, e);
447
- }
448
- else {
449
- this.eventHandler.emitEvent(EventType.LOGIN_FAILURE, InteractionType.Popup, null, e);
450
- }
451
- atPopupMeasurement.end({
452
- success: false,
453
- }, e);
454
- // Since this function is syncronous we need to reject
455
- return Promise.reject(e);
456
- });
457
- }
458
- trackPageVisibilityWithMeasurement() {
459
- const measurement = this.ssoSilentMeasurement ||
460
- this.acquireTokenByCodeAsyncMeasurement;
461
- if (!measurement) {
462
- return;
463
- }
464
- this.logger.info("Perf: Visibility change detected in ", measurement.event.name);
465
- measurement.increment({
466
- visibilityChangeCount: 1,
467
- });
468
- }
469
- // #endregion
470
- // #region Silent Flow
471
- /**
472
- * This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
473
- * - Any browser using a form of Intelligent Tracking Prevention
474
- * - If there is not an established session with the service
475
- *
476
- * In these cases, the request must be done inside a popup or full frame redirect.
477
- *
478
- * For the cases where interaction is required, you cannot send a request with prompt=none.
479
- *
480
- * If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
481
- * you session on the server still exists.
482
- * @param request {@link SsoSilentRequest}
483
- *
484
- * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
485
- */
486
- async ssoSilent(request) {
487
- const correlationId = this.getRequestCorrelationId(request);
488
- const validRequest = {
489
- ...request,
490
- // will be PromptValue.NONE or PromptValue.NO_SESSION
491
- prompt: request.prompt,
492
- correlationId: correlationId,
493
- };
494
- this.ssoSilentMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.SsoSilent, correlationId);
495
- this.ssoSilentMeasurement?.add({
496
- scenarioId: request.scenarioId,
497
- accountType: getAccountType(request.account),
498
- });
499
- preflightCheck(this.initialized, this.ssoSilentMeasurement);
500
- this.ssoSilentMeasurement?.increment({
501
- visibilityChangeCount: 0,
502
- });
503
- document.addEventListener("visibilitychange", this.trackPageVisibilityWithMeasurement);
504
- this.logger.verbose("ssoSilent called", correlationId);
505
- this.eventHandler.emitEvent(EventType.SSO_SILENT_START, InteractionType.Silent, validRequest);
506
- let result;
507
- if (this.canUseNative(validRequest)) {
508
- result = this.acquireTokenNative(validRequest, ApiId.ssoSilent).catch((e) => {
509
- // If native token acquisition fails for availability reasons fallback to standard flow
510
- if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
511
- this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
512
- const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
513
- return silentIframeClient.acquireToken(validRequest);
514
- }
515
- throw e;
516
- });
517
- }
518
- else {
519
- const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
520
- result = silentIframeClient.acquireToken(validRequest);
521
- }
522
- return result
523
- .then((response) => {
524
- this.eventHandler.emitEvent(EventType.SSO_SILENT_SUCCESS, InteractionType.Silent, response);
525
- this.ssoSilentMeasurement?.end({
526
- success: true,
527
- isNativeBroker: response.fromNativeBroker,
528
- requestId: response.requestId,
529
- accessTokenSize: response.accessToken.length,
530
- idTokenSize: response.idToken.length,
531
- accountType: getAccountType(response.account),
532
- });
533
- return response;
534
- })
535
- .catch((e) => {
536
- this.eventHandler.emitEvent(EventType.SSO_SILENT_FAILURE, InteractionType.Silent, null, e);
537
- this.ssoSilentMeasurement?.end({
538
- success: false,
539
- }, e);
540
- throw e;
541
- })
542
- .finally(() => {
543
- document.removeEventListener("visibilitychange", this.trackPageVisibilityWithMeasurement);
544
- });
545
- }
546
- /**
547
- * This function redeems an authorization code (passed as code) from the eSTS token endpoint.
548
- * This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
549
- * This API is not indended for normal authorization code acquisition and redemption.
550
- *
551
- * Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
552
- *
553
- * @param request {@link AuthorizationCodeRequest}
554
- * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
555
- */
556
- async acquireTokenByCode(request) {
557
- const correlationId = this.getRequestCorrelationId(request);
558
- this.logger.trace("acquireTokenByCode called", correlationId);
559
- const atbcMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenByCode, correlationId);
560
- preflightCheck(this.initialized, atbcMeasurement);
561
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_BY_CODE_START, InteractionType.Silent, request);
562
- atbcMeasurement.add({ scenarioId: request.scenarioId });
563
- try {
564
- if (request.code && request.nativeAccountId) {
565
- // Throw error in case server returns both spa_code and spa_accountid in exchange for auth code.
566
- throw createBrowserAuthError(spaCodeAndNativeAccountIdPresent);
567
- }
568
- else if (request.code) {
569
- const hybridAuthCode = request.code;
570
- let response = this.hybridAuthCodeResponses.get(hybridAuthCode);
571
- if (!response) {
572
- this.logger.verbose("Initiating new acquireTokenByCode request", correlationId);
573
- response = this.acquireTokenByCodeAsync({
574
- ...request,
575
- correlationId,
576
- })
577
- .then((result) => {
578
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_BY_CODE_SUCCESS, InteractionType.Silent, result);
579
- this.hybridAuthCodeResponses.delete(hybridAuthCode);
580
- atbcMeasurement.end({
581
- success: true,
582
- isNativeBroker: result.fromNativeBroker,
583
- requestId: result.requestId,
584
- accessTokenSize: result.accessToken.length,
585
- idTokenSize: result.idToken.length,
586
- accountType: getAccountType(result.account),
587
- });
588
- return result;
589
- })
590
- .catch((error) => {
591
- this.hybridAuthCodeResponses.delete(hybridAuthCode);
592
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_BY_CODE_FAILURE, InteractionType.Silent, null, error);
593
- atbcMeasurement.end({
594
- success: false,
595
- }, error);
596
- throw error;
597
- });
598
- this.hybridAuthCodeResponses.set(hybridAuthCode, response);
599
- }
600
- else {
601
- this.logger.verbose("Existing acquireTokenByCode request found", correlationId);
602
- atbcMeasurement.discard();
603
- }
604
- return await response;
605
- }
606
- else if (request.nativeAccountId) {
607
- if (this.canUseNative(request, request.nativeAccountId)) {
608
- const result = await this.acquireTokenNative({
609
- ...request,
610
- correlationId,
611
- }, ApiId.acquireTokenByCode, request.nativeAccountId).catch((e) => {
612
- // If native token acquisition fails for availability reasons fallback to standard flow
613
- if (e instanceof NativeAuthError &&
614
- isFatalNativeAuthError(e)) {
615
- this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
616
- }
617
- throw e;
618
- });
619
- atbcMeasurement.end({
620
- accountType: getAccountType(result.account),
621
- success: true,
622
- });
623
- return result;
624
- }
625
- else {
626
- throw createBrowserAuthError(unableToAcquireTokenFromNativePlatform);
627
- }
628
- }
629
- else {
630
- throw createBrowserAuthError(authCodeOrNativeAccountIdRequired);
631
- }
632
- }
633
- catch (e) {
634
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_BY_CODE_FAILURE, InteractionType.Silent, null, e);
635
- atbcMeasurement.end({
636
- success: false,
637
- }, e);
638
- throw e;
639
- }
640
- }
641
- /**
642
- * Creates a SilentAuthCodeClient to redeem an authorization code.
643
- * @param request
644
- * @returns Result of the operation to redeem the authorization code
645
- */
646
- async acquireTokenByCodeAsync(request) {
647
- this.logger.trace("acquireTokenByCodeAsync called", request.correlationId);
648
- this.acquireTokenByCodeAsyncMeasurement =
649
- this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenByCodeAsync, request.correlationId);
650
- this.acquireTokenByCodeAsyncMeasurement?.increment({
651
- visibilityChangeCount: 0,
652
- });
653
- document.addEventListener("visibilitychange", this.trackPageVisibilityWithMeasurement);
654
- const silentAuthCodeClient = this.createSilentAuthCodeClient(request.correlationId);
655
- const silentTokenResult = await silentAuthCodeClient
656
- .acquireToken(request)
657
- .then((response) => {
658
- this.acquireTokenByCodeAsyncMeasurement?.end({
659
- success: true,
660
- fromCache: response.fromCache,
661
- isNativeBroker: response.fromNativeBroker,
662
- requestId: response.requestId,
663
- });
664
- return response;
665
- })
666
- .catch((tokenRenewalError) => {
667
- this.acquireTokenByCodeAsyncMeasurement?.end({
668
- success: false,
669
- }, tokenRenewalError);
670
- throw tokenRenewalError;
671
- })
672
- .finally(() => {
673
- document.removeEventListener("visibilitychange", this.trackPageVisibilityWithMeasurement);
674
- });
675
- return silentTokenResult;
676
- }
677
- /**
678
- * Attempt to acquire an access token from the cache
679
- * @param silentCacheClient SilentCacheClient
680
- * @param commonRequest CommonSilentFlowRequest
681
- * @param silentRequest SilentRequest
682
- * @returns A promise that, when resolved, returns the access token
683
- */
684
- async acquireTokenFromCache(commonRequest, cacheLookupPolicy) {
685
- this.performanceClient.addQueueMeasurement(PerformanceEvents.AcquireTokenFromCache, commonRequest.correlationId);
686
- switch (cacheLookupPolicy) {
687
- case CacheLookupPolicy.Default:
688
- case CacheLookupPolicy.AccessToken:
689
- case CacheLookupPolicy.AccessTokenAndRefreshToken:
690
- const silentCacheClient = this.createSilentCacheClient(commonRequest.correlationId);
691
- return invokeAsync(silentCacheClient.acquireToken.bind(silentCacheClient), PerformanceEvents.SilentCacheClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
692
- default:
693
- throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
694
- }
695
- }
696
- /**
697
- * Attempt to acquire an access token via a refresh token
698
- * @param commonRequest CommonSilentFlowRequest
699
- * @param cacheLookupPolicy CacheLookupPolicy
700
- * @returns A promise that, when resolved, returns the access token
701
- */
702
- async acquireTokenByRefreshToken(commonRequest, cacheLookupPolicy) {
703
- this.performanceClient.addQueueMeasurement(PerformanceEvents.AcquireTokenByRefreshToken, commonRequest.correlationId);
704
- switch (cacheLookupPolicy) {
705
- case CacheLookupPolicy.Default:
706
- case CacheLookupPolicy.AccessTokenAndRefreshToken:
707
- case CacheLookupPolicy.RefreshToken:
708
- case CacheLookupPolicy.RefreshTokenAndNetwork:
709
- const silentRefreshClient = this.createSilentRefreshClient(commonRequest.correlationId);
710
- return invokeAsync(silentRefreshClient.acquireToken.bind(silentRefreshClient), PerformanceEvents.SilentRefreshClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
711
- default:
712
- throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
713
- }
714
- }
715
- /**
716
- * Attempt to acquire an access token via an iframe
717
- * @param request CommonSilentFlowRequest
718
- * @returns A promise that, when resolved, returns the access token
719
- */
720
- async acquireTokenBySilentIframe(request) {
721
- this.performanceClient.addQueueMeasurement(PerformanceEvents.AcquireTokenBySilentIframe, request.correlationId);
722
- const silentIframeClient = this.createSilentIframeClient(request.correlationId);
723
- return invokeAsync(silentIframeClient.acquireToken.bind(silentIframeClient), PerformanceEvents.SilentIframeClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(request);
724
- }
725
- // #endregion
726
- // #region Logout
727
- /**
728
- * Deprecated logout function. Use logoutRedirect or logoutPopup instead
729
- * @param logoutRequest
730
- * @deprecated
731
- */
732
- async logout(logoutRequest) {
733
- const correlationId = this.getRequestCorrelationId(logoutRequest);
734
- this.logger.warning("logout API is deprecated and will be removed in msal-browser v3.0.0. Use logoutRedirect instead.", correlationId);
735
- return this.logoutRedirect({
736
- correlationId,
737
- ...logoutRequest,
738
- });
739
- }
740
- /**
741
- * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
742
- * Default behaviour is to redirect the user to `window.location.href`.
743
- * @param logoutRequest
744
- */
745
- async logoutRedirect(logoutRequest) {
746
- const correlationId = this.getRequestCorrelationId(logoutRequest);
747
- redirectPreflightCheck(this.initialized, this.config);
748
- this.browserStorage.setInteractionInProgress(true);
749
- const redirectClient = this.createRedirectClient(correlationId);
750
- return redirectClient.logout(logoutRequest);
751
- }
752
- /**
753
- * Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
754
- * @param logoutRequest
755
- */
756
- logoutPopup(logoutRequest) {
757
- try {
758
- const correlationId = this.getRequestCorrelationId(logoutRequest);
759
- preflightCheck$1(this.initialized);
760
- this.browserStorage.setInteractionInProgress(true);
761
- const popupClient = this.createPopupClient(correlationId);
762
- return popupClient.logout(logoutRequest);
763
- }
764
- catch (e) {
765
- // Since this function is syncronous we need to reject
766
- return Promise.reject(e);
767
- }
768
- }
769
- /**
770
- * Creates a cache interaction client to clear broswer cache.
771
- * @param logoutRequest
772
- */
773
- async clearCache(logoutRequest) {
774
- const correlationId = this.getRequestCorrelationId(logoutRequest);
775
- const cacheClient = this.createSilentCacheClient(correlationId);
776
- return cacheClient.logout(logoutRequest);
777
- }
778
- // #endregion
779
- // #region Account APIs
780
- /**
781
- * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
782
- * @param accountFilter - (Optional) filter to narrow down the accounts returned
783
- * @returns Array of AccountInfo objects in cache
784
- */
785
- getAllAccounts(accountFilter) {
786
- return getAllAccounts(this.logger, this.browserStorage, this.isBrowserEnvironment, accountFilter);
787
- }
788
- /**
789
- * Returns the first account found in the cache that matches the account filter passed in.
790
- * @param accountFilter
791
- * @returns The first account found in the cache matching the provided filter or null if no account could be found.
792
- */
793
- getAccount(accountFilter) {
794
- return getAccount(accountFilter, this.logger, this.browserStorage);
795
- }
796
- /**
797
- * Returns the signed in account matching username.
798
- * (the account object is created at the time of successful login)
799
- * or null when no matching account is found.
800
- * This API is provided for convenience but getAccountById should be used for best reliability
801
- * @param username
802
- * @returns The account object stored in MSAL
803
- */
804
- getAccountByUsername(username) {
805
- return getAccountByUsername(username, this.logger, this.browserStorage);
806
- }
807
- /**
808
- * Returns the signed in account matching homeAccountId.
809
- * (the account object is created at the time of successful login)
810
- * or null when no matching account is found
811
- * @param homeAccountId
812
- * @returns The account object stored in MSAL
813
- */
814
- getAccountByHomeId(homeAccountId) {
815
- return getAccountByHomeId(homeAccountId, this.logger, this.browserStorage);
816
- }
817
- /**
818
- * Returns the signed in account matching localAccountId.
819
- * (the account object is created at the time of successful login)
820
- * or null when no matching account is found
821
- * @param localAccountId
822
- * @returns The account object stored in MSAL
823
- */
824
- getAccountByLocalId(localAccountId) {
825
- return getAccountByLocalId(localAccountId, this.logger, this.browserStorage);
826
- }
827
- /**
828
- * Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
829
- * @param account
830
- */
831
- setActiveAccount(account) {
832
- setActiveAccount(account, this.browserStorage);
833
- }
834
- /**
835
- * Gets the currently active account
836
- */
837
- getActiveAccount() {
838
- return getActiveAccount(this.browserStorage);
839
- }
840
- // #endregion
841
- /**
842
- * Hydrates the cache with the tokens from an AuthenticationResult
843
- * @param result
844
- * @param request
845
- * @returns
846
- */
847
- async hydrateCache(result, request) {
848
- this.logger.verbose("hydrateCache called");
849
- // Account gets saved to browser storage regardless of native or not
850
- const accountEntity = AccountEntity.createFromAccountInfo(result.account, result.cloudGraphHostName, result.msGraphHost);
851
- this.browserStorage.setAccount(accountEntity);
852
- if (result.fromNativeBroker) {
853
- this.logger.verbose("Response was from native broker, storing in-memory");
854
- // Tokens from native broker are stored in-memory
855
- return this.nativeInternalStorage.hydrateCache(result, request);
856
- }
857
- else {
858
- return this.browserStorage.hydrateCache(result, request);
859
- }
860
- }
861
- // #region Helpers
862
- /**
863
- * Acquire a token from native device (e.g. WAM)
864
- * @param request
865
- */
866
- async acquireTokenNative(request, apiId, accountId) {
867
- this.logger.trace("acquireTokenNative called");
868
- if (!this.nativeExtensionProvider) {
869
- throw createBrowserAuthError(nativeConnectionNotEstablished);
870
- }
871
- const nativeClient = new NativeInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, apiId, this.performanceClient, this.nativeExtensionProvider, accountId || this.getNativeAccountId(request), this.nativeInternalStorage, request.correlationId);
872
- return nativeClient.acquireToken(request);
873
- }
874
- /**
875
- * Returns boolean indicating if this request can use the native broker
876
- * @param request
877
- */
878
- canUseNative(request, accountId) {
879
- this.logger.trace("canUseNative called");
880
- if (!NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeExtensionProvider, request.authenticationScheme)) {
881
- this.logger.trace("canUseNative: isNativeAvailable returned false, returning false");
882
- return false;
883
- }
884
- if (request.prompt) {
885
- switch (request.prompt) {
886
- case PromptValue.NONE:
887
- case PromptValue.CONSENT:
888
- case PromptValue.LOGIN:
889
- this.logger.trace("canUseNative: prompt is compatible with native flow");
890
- break;
891
- default:
892
- this.logger.trace(`canUseNative: prompt = ${request.prompt} is not compatible with native flow, returning false`);
893
- return false;
894
- }
895
- }
896
- if (!accountId && !this.getNativeAccountId(request)) {
897
- this.logger.trace("canUseNative: nativeAccountId is not available, returning false");
898
- return false;
899
- }
900
- return true;
901
- }
902
- /**
903
- * Get the native accountId from the account
904
- * @param request
905
- * @returns
906
- */
907
- getNativeAccountId(request) {
908
- const account = request.account ||
909
- this.getAccount({
910
- loginHint: request.loginHint,
911
- sid: request.sid,
912
- }) ||
913
- this.getActiveAccount();
914
- return (account && account.nativeAccountId) || "";
915
- }
916
- /**
917
- * Returns new instance of the Popup Interaction Client
918
- * @param correlationId
919
- */
920
- createPopupClient(correlationId) {
921
- return new PopupClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, this.nativeExtensionProvider, correlationId);
922
- }
923
- /**
924
- * Returns new instance of the Redirect Interaction Client
925
- * @param correlationId
926
- */
927
- createRedirectClient(correlationId) {
928
- return new RedirectClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, this.nativeExtensionProvider, correlationId);
929
- }
930
- /**
931
- * Returns new instance of the Silent Iframe Interaction Client
932
- * @param correlationId
933
- */
934
- createSilentIframeClient(correlationId) {
935
- return new SilentIframeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.ssoSilent, this.performanceClient, this.nativeInternalStorage, this.nativeExtensionProvider, correlationId);
936
- }
937
- /**
938
- * Returns new instance of the Silent Cache Interaction Client
939
- */
940
- createSilentCacheClient(correlationId) {
941
- return new SilentCacheClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeExtensionProvider, correlationId);
942
- }
943
- /**
944
- * Returns new instance of the Silent Refresh Interaction Client
945
- */
946
- createSilentRefreshClient(correlationId) {
947
- return new SilentRefreshClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeExtensionProvider, correlationId);
948
- }
949
- /**
950
- * Returns new instance of the Silent AuthCode Interaction Client
951
- */
952
- createSilentAuthCodeClient(correlationId) {
953
- return new SilentAuthCodeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenByCode, this.performanceClient, this.nativeExtensionProvider, correlationId);
954
- }
955
- /**
956
- * Adds event callbacks to array
957
- * @param callback
958
- */
959
- addEventCallback(callback) {
960
- return this.eventHandler.addEventCallback(callback);
961
- }
962
- /**
963
- * Removes callback with provided id from callback array
964
- * @param callbackId
965
- */
966
- removeEventCallback(callbackId) {
967
- this.eventHandler.removeEventCallback(callbackId);
968
- }
969
- /**
970
- * Registers a callback to receive performance events.
971
- *
972
- * @param {PerformanceCallbackFunction} callback
973
- * @returns {string}
974
- */
975
- addPerformanceCallback(callback) {
976
- return this.performanceClient.addPerformanceCallback(callback);
977
- }
978
- /**
979
- * Removes a callback registered with addPerformanceCallback.
980
- *
981
- * @param {string} callbackId
982
- * @returns {boolean}
983
- */
984
- removePerformanceCallback(callbackId) {
985
- return this.performanceClient.removePerformanceCallback(callbackId);
986
- }
987
- /**
988
- * Adds event listener that emits an event when a user account is added or removed from localstorage in a different browser tab or window
989
- */
990
- enableAccountStorageEvents() {
991
- this.eventHandler.enableAccountStorageEvents();
992
- }
993
- /**
994
- * Removes event listener that emits an event when a user account is added or removed from localstorage in a different browser tab or window
995
- */
996
- disableAccountStorageEvents() {
997
- this.eventHandler.disableAccountStorageEvents();
998
- }
999
- /**
1000
- * Gets the token cache for the application.
1001
- */
1002
- getTokenCache() {
1003
- return this.tokenCache;
1004
- }
1005
- /**
1006
- * Returns the logger instance
1007
- */
1008
- getLogger() {
1009
- return this.logger;
1010
- }
1011
- /**
1012
- * Replaces the default logger set in configurations with new Logger with new configurations
1013
- * @param logger Logger instance
1014
- */
1015
- setLogger(logger) {
1016
- this.logger = logger;
1017
- }
1018
- /**
1019
- * Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
1020
- * @param sku
1021
- * @param version
1022
- */
1023
- initializeWrapperLibrary(sku, version) {
1024
- // Validate the SKU passed in is one we expect
1025
- this.browserStorage.setWrapperMetadata(sku, version);
1026
- }
1027
- /**
1028
- * Sets navigation client
1029
- * @param navigationClient
1030
- */
1031
- setNavigationClient(navigationClient) {
1032
- this.navigationClient = navigationClient;
1033
- }
1034
- /**
1035
- * Returns the configuration object
1036
- */
1037
- getConfiguration() {
1038
- return this.config;
1039
- }
1040
- /**
1041
- * Returns the performance client
1042
- */
1043
- getPerformanceClient() {
1044
- return this.performanceClient;
1045
- }
1046
- /**
1047
- * Returns the browser env indicator
1048
- */
1049
- isBrowserEnv() {
1050
- return this.isBrowserEnvironment;
1051
- }
1052
- /**
1053
- * Returns the event handler
1054
- */
1055
- getEventHandler() {
1056
- return this.eventHandler;
1057
- }
1058
- /**
1059
- * Generates a correlation id for a request if none is provided.
1060
- *
1061
- * @protected
1062
- * @param {?Partial<BaseAuthRequest>} [request]
1063
- * @returns {string}
1064
- */
1065
- getRequestCorrelationId(request) {
1066
- if (request?.correlationId) {
1067
- return request.correlationId;
1068
- }
1069
- if (this.isBrowserEnvironment) {
1070
- return createNewGuid();
1071
- }
1072
- /*
1073
- * Included for fallback for non-browser environments,
1074
- * and to ensure this method always returns a string.
1075
- */
1076
- return Constants.EMPTY_STRING;
1077
- }
1078
- // #endregion
1079
- /**
1080
- * Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
1081
- * any code that follows this function will not execute.
1082
- *
1083
- * 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
1084
- * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
1085
- *
1086
- * @param request
1087
- */
1088
- async loginRedirect(request) {
1089
- const correlationId = this.getRequestCorrelationId(request);
1090
- this.logger.verbose("loginRedirect called", correlationId);
1091
- return this.acquireTokenRedirect({
1092
- correlationId,
1093
- ...(request || DEFAULT_REQUEST),
1094
- });
1095
- }
1096
- /**
1097
- * Use when initiating the login process via opening a popup window in the user's browser
1098
- *
1099
- * @param request
1100
- *
1101
- * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
1102
- */
1103
- loginPopup(request) {
1104
- const correlationId = this.getRequestCorrelationId(request);
1105
- this.logger.verbose("loginPopup called", correlationId);
1106
- return this.acquireTokenPopup({
1107
- correlationId,
1108
- ...(request || DEFAULT_REQUEST),
1109
- });
1110
- }
1111
- /**
1112
- * Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
1113
- *
1114
- * @param {@link (SilentRequest:type)}
1115
- * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
1116
- */
1117
- async acquireTokenSilent(request) {
1118
- const correlationId = this.getRequestCorrelationId(request);
1119
- const atsMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenSilent, correlationId);
1120
- atsMeasurement.add({
1121
- cacheLookupPolicy: request.cacheLookupPolicy,
1122
- scenarioId: request.scenarioId,
1123
- });
1124
- preflightCheck(this.initialized, atsMeasurement);
1125
- this.logger.verbose("acquireTokenSilent called", correlationId);
1126
- const account = request.account || this.getActiveAccount();
1127
- if (!account) {
1128
- throw createBrowserAuthError(noAccountError);
1129
- }
1130
- atsMeasurement.add({ accountType: getAccountType(account) });
1131
- const thumbprint = {
1132
- clientId: this.config.auth.clientId,
1133
- authority: request.authority || Constants.EMPTY_STRING,
1134
- scopes: request.scopes,
1135
- homeAccountIdentifier: account.homeAccountId,
1136
- claims: request.claims,
1137
- authenticationScheme: request.authenticationScheme,
1138
- resourceRequestMethod: request.resourceRequestMethod,
1139
- resourceRequestUri: request.resourceRequestUri,
1140
- shrClaims: request.shrClaims,
1141
- sshKid: request.sshKid,
1142
- shrOptions: request.shrOptions,
1143
- };
1144
- const silentRequestKey = JSON.stringify(thumbprint);
1145
- const cachedResponse = this.activeSilentTokenRequests.get(silentRequestKey);
1146
- if (typeof cachedResponse === "undefined") {
1147
- this.logger.verbose("acquireTokenSilent called for the first time, storing active request", correlationId);
1148
- const response = invokeAsync(this.acquireTokenSilentAsync.bind(this), PerformanceEvents.AcquireTokenSilentAsync, this.logger, this.performanceClient, correlationId)({
1149
- ...request,
1150
- correlationId,
1151
- }, account)
1152
- .then((result) => {
1153
- this.activeSilentTokenRequests.delete(silentRequestKey);
1154
- atsMeasurement.end({
1155
- success: true,
1156
- fromCache: result.fromCache,
1157
- isNativeBroker: result.fromNativeBroker,
1158
- cacheLookupPolicy: request.cacheLookupPolicy,
1159
- requestId: result.requestId,
1160
- accessTokenSize: result.accessToken.length,
1161
- idTokenSize: result.idToken.length,
1162
- });
1163
- return result;
1164
- })
1165
- .catch((error) => {
1166
- this.activeSilentTokenRequests.delete(silentRequestKey);
1167
- atsMeasurement.end({
1168
- success: false,
1169
- }, error);
1170
- throw error;
1171
- });
1172
- this.activeSilentTokenRequests.set(silentRequestKey, response);
1173
- return {
1174
- ...(await response),
1175
- state: request.state,
1176
- };
1177
- }
1178
- else {
1179
- this.logger.verbose("acquireTokenSilent has been called previously, returning the result from the first call", correlationId);
1180
- // Discard measurements for memoized calls, as they are usually only a couple of ms and will artificially deflate metrics
1181
- atsMeasurement.discard();
1182
- return {
1183
- ...(await cachedResponse),
1184
- state: request.state,
1185
- };
1186
- }
1187
- }
1188
- /**
1189
- * Silently acquire an access token for a given set of scopes. Will use cached token if available, otherwise will attempt to acquire a new token from the network via refresh token.
1190
- * @param {@link (SilentRequest:type)}
1191
- * @param {@link (AccountInfo:type)}
1192
- * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse}
1193
- */
1194
- async acquireTokenSilentAsync(request, account) {
1195
- const trackPageVisibility = () => this.trackPageVisibility(request.correlationId);
1196
- this.performanceClient.addQueueMeasurement(PerformanceEvents.AcquireTokenSilentAsync, request.correlationId);
1197
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, InteractionType.Silent, request);
1198
- if (request.correlationId) {
1199
- this.performanceClient.incrementFields({ visibilityChangeCount: 0 }, request.correlationId);
1200
- }
1201
- document.addEventListener("visibilitychange", trackPageVisibility);
1202
- const silentRequest = await invokeAsync(initializeSilentRequest, PerformanceEvents.InitializeSilentRequest, this.logger, this.performanceClient, request.correlationId)(request, account, this.config, this.performanceClient, this.logger);
1203
- const cacheLookupPolicy = request.cacheLookupPolicy || CacheLookupPolicy.Default;
1204
- const result = this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy).catch(async (refreshTokenError) => {
1205
- const shouldTryToResolveSilently = checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy);
1206
- if (shouldTryToResolveSilently) {
1207
- if (!this.activeIframeRequest) {
1208
- let _resolve;
1209
- // Always set the active request tracker immediately after checking it to prevent races
1210
- this.activeIframeRequest = [
1211
- new Promise((resolve) => {
1212
- _resolve = resolve;
1213
- }),
1214
- silentRequest.correlationId,
1215
- ];
1216
- this.logger.verbose("Refresh token expired/invalid or CacheLookupPolicy is set to Skip, attempting acquire token by iframe.", silentRequest.correlationId);
1217
- return invokeAsync(this.acquireTokenBySilentIframe.bind(this), PerformanceEvents.AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest)
1218
- .then((iframeResult) => {
1219
- _resolve(true);
1220
- return iframeResult;
1221
- })
1222
- .catch((e) => {
1223
- _resolve(false);
1224
- throw e;
1225
- })
1226
- .finally(() => {
1227
- this.activeIframeRequest = undefined;
1228
- });
1229
- }
1230
- else if (cacheLookupPolicy !== CacheLookupPolicy.Skip) {
1231
- const [activePromise, activeCorrelationId] = this.activeIframeRequest;
1232
- this.logger.verbose(`Iframe request is already in progress, awaiting resolution for request with correlationId: ${activeCorrelationId}`, silentRequest.correlationId);
1233
- const awaitConcurrentIframeMeasure = this.performanceClient.startMeasurement(PerformanceEvents.AwaitConcurrentIframe, silentRequest.correlationId);
1234
- awaitConcurrentIframeMeasure.add({
1235
- awaitIframeCorrelationId: activeCorrelationId,
1236
- });
1237
- const activePromiseResult = await activePromise;
1238
- awaitConcurrentIframeMeasure.end({
1239
- success: activePromiseResult,
1240
- });
1241
- if (activePromiseResult) {
1242
- this.logger.verbose(`Parallel iframe request with correlationId: ${activeCorrelationId} succeeded. Retrying cache and/or RT redemption`, silentRequest.correlationId);
1243
- // Retry cache lookup and/or RT exchange after iframe completes
1244
- return this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy);
1245
- }
1246
- else {
1247
- this.logger.info(`Iframe request with correlationId: ${activeCorrelationId} failed. Interaction is required.`);
1248
- // If previous iframe request failed, it's unlikely to succeed this time. Throw original error.
1249
- throw refreshTokenError;
1250
- }
1251
- }
1252
- else {
1253
- // Cache policy set to skip and another iframe request is already in progress
1254
- this.logger.warning("Another iframe request is currently in progress and CacheLookupPolicy is set to Skip. This may result in degraded performance and/or reliability for both calls. Please consider changing the CacheLookupPolicy to take advantage of request queuing and token cache.", silentRequest.correlationId);
1255
- return invokeAsync(this.acquireTokenBySilentIframe.bind(this), PerformanceEvents.AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest);
1256
- }
1257
- }
1258
- else {
1259
- // Error cannot be silently resolved or iframe renewal is not allowed, interaction required
1260
- throw refreshTokenError;
1261
- }
1262
- });
1263
- return result
1264
- .then((response) => {
1265
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, InteractionType.Silent, response);
1266
- if (request.correlationId) {
1267
- this.performanceClient.addFields({
1268
- fromCache: response.fromCache,
1269
- isNativeBroker: response.fromNativeBroker,
1270
- requestId: response.requestId,
1271
- }, request.correlationId);
1272
- }
1273
- return response;
1274
- })
1275
- .catch((tokenRenewalError) => {
1276
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, InteractionType.Silent, null, tokenRenewalError);
1277
- throw tokenRenewalError;
1278
- })
1279
- .finally(() => {
1280
- document.removeEventListener("visibilitychange", trackPageVisibility);
1281
- });
1282
- }
1283
- /**
1284
- * AcquireTokenSilent without the iframe fallback. This is used to enable the correct fallbacks in cases where there's a potential for multiple silent requests to be made in parallel and prevent those requests from making concurrent iframe requests.
1285
- * @param silentRequest
1286
- * @param cacheLookupPolicy
1287
- * @returns
1288
- */
1289
- async acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy) {
1290
- if (NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeExtensionProvider, silentRequest.authenticationScheme) &&
1291
- silentRequest.account.nativeAccountId) {
1292
- this.logger.verbose("acquireTokenSilent - attempting to acquire token from native platform");
1293
- return this.acquireTokenNative(silentRequest, ApiId.acquireTokenSilent_silentFlow).catch(async (e) => {
1294
- // If native token acquisition fails for availability reasons fallback to web flow
1295
- if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
1296
- this.logger.verbose("acquireTokenSilent - native platform unavailable, falling back to web flow");
1297
- this.nativeExtensionProvider = undefined; // Prevent future requests from continuing to attempt
1298
- // Cache will not contain tokens, given that previous WAM requests succeeded. Skip cache and RT renewal and go straight to iframe renewal
1299
- throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
1300
- }
1301
- throw e;
1302
- });
1303
- }
1304
- else {
1305
- this.logger.verbose("acquireTokenSilent - attempting to acquire token from web flow");
1306
- return invokeAsync(this.acquireTokenFromCache.bind(this), PerformanceEvents.AcquireTokenFromCache, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy).catch((cacheError) => {
1307
- if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
1308
- throw cacheError;
1309
- }
1310
- this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_NETWORK_START, InteractionType.Silent, silentRequest);
1311
- return invokeAsync(this.acquireTokenByRefreshToken.bind(this), PerformanceEvents.AcquireTokenByRefreshToken, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy);
1312
- });
1313
- }
1314
- }
1315
- }
1316
- /**
1317
- * Determines whether an error thrown by the refresh token endpoint can be resolved without interaction
1318
- * @param refreshTokenError
1319
- * @param silentRequest
1320
- * @param cacheLookupPolicy
1321
- * @returns
1322
- */
1323
- function checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy) {
1324
- const noInteractionRequired = !(refreshTokenError instanceof InteractionRequiredAuthError &&
1325
- // For refresh token errors, bad_token does not always require interaction (silently resolvable)
1326
- refreshTokenError.subError !==
1327
- InteractionRequiredAuthErrorCodes.badToken);
1328
- // Errors that result when the refresh token needs to be replaced
1329
- const refreshTokenRefreshRequired = refreshTokenError.errorCode === BrowserConstants.INVALID_GRANT_ERROR ||
1330
- refreshTokenError.errorCode ===
1331
- ClientAuthErrorCodes.tokenRefreshRequired;
1332
- // Errors that may be resolved before falling back to interaction (through iframe renewal)
1333
- const isSilentlyResolvable = (noInteractionRequired && refreshTokenRefreshRequired) ||
1334
- refreshTokenError.errorCode ===
1335
- InteractionRequiredAuthErrorCodes.noTokensFound ||
1336
- refreshTokenError.errorCode ===
1337
- InteractionRequiredAuthErrorCodes.refreshTokenExpired;
1338
- // Only these policies allow for an iframe renewal attempt
1339
- const tryIframeRenewal = iFrameRenewalPolicies.includes(cacheLookupPolicy);
1340
- return isSilentlyResolvable && tryIframeRenewal;
26
+ /*
27
+ * Copyright (c) Microsoft Corporation. All rights reserved.
28
+ * Licensed under the MIT License.
29
+ */
30
+ function getAccountType(account) {
31
+ const idTokenClaims = account?.idTokenClaims;
32
+ if (idTokenClaims?.tfp || idTokenClaims?.acr) {
33
+ return "B2C";
34
+ }
35
+ if (!idTokenClaims?.tid) {
36
+ return undefined;
37
+ }
38
+ else if (idTokenClaims?.tid === "9188040d-6c67-4c5b-b112-36a304b66dad") {
39
+ return "MSA";
40
+ }
41
+ return "AAD";
42
+ }
43
+ function preflightCheck(initialized, performanceEvent) {
44
+ try {
45
+ preflightCheck$1(initialized);
46
+ }
47
+ catch (e) {
48
+ performanceEvent.end({ success: false }, e);
49
+ throw e;
50
+ }
51
+ }
52
+ class StandardController {
53
+ /**
54
+ * @constructor
55
+ * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
56
+ *
57
+ * Important attributes in the Configuration object for auth are:
58
+ * - 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
59
+ * - authority: the authority URL for your application.
60
+ * - redirect_uri: the uri of your application registered in the portal.
61
+ *
62
+ * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
63
+ * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
64
+ * 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).
65
+ * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
66
+ * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
67
+ * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
68
+ *
69
+ * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
70
+ * Full B2C functionality will be available in this library in future versions.
71
+ *
72
+ * @param configuration Object for the MSAL PublicClientApplication instance
73
+ */
74
+ constructor(operatingContext) {
75
+ this.operatingContext = operatingContext;
76
+ this.isBrowserEnvironment =
77
+ this.operatingContext.isBrowserEnvironment();
78
+ // Set the configuration.
79
+ this.config = operatingContext.getConfig();
80
+ this.initialized = false;
81
+ // Initialize logger
82
+ this.logger = this.operatingContext.getLogger();
83
+ // Initialize the network module class.
84
+ this.networkClient = this.config.system.networkClient;
85
+ // Initialize the navigation client class.
86
+ this.navigationClient = this.config.system.navigationClient;
87
+ // Initialize redirectResponse Map
88
+ this.redirectResponse = new Map();
89
+ // Initial hybrid spa map
90
+ this.hybridAuthCodeResponses = new Map();
91
+ // Initialize performance client
92
+ this.performanceClient = this.config.telemetry.client;
93
+ // Initialize the crypto class.
94
+ this.browserCrypto = this.isBrowserEnvironment
95
+ ? new CryptoOps(this.logger, this.performanceClient)
96
+ : DEFAULT_CRYPTO_IMPLEMENTATION;
97
+ this.eventHandler = new EventHandler(this.logger, this.browserCrypto);
98
+ // Initialize the browser storage class.
99
+ this.browserStorage = this.isBrowserEnvironment
100
+ ? new BrowserCacheManager(this.config.auth.clientId, this.config.cache, this.browserCrypto, this.logger, buildStaticAuthorityOptions(this.config.auth), this.performanceClient)
101
+ : DEFAULT_BROWSER_CACHE_MANAGER(this.config.auth.clientId, this.logger);
102
+ // initialize in memory storage for native flows
103
+ const nativeCacheOptions = {
104
+ cacheLocation: BrowserCacheLocation.MemoryStorage,
105
+ temporaryCacheLocation: BrowserCacheLocation.MemoryStorage,
106
+ storeAuthStateInCookie: false,
107
+ secureCookies: false,
108
+ cacheMigrationEnabled: false,
109
+ claimsBasedCachingEnabled: false,
110
+ };
111
+ this.nativeInternalStorage = new BrowserCacheManager(this.config.auth.clientId, nativeCacheOptions, this.browserCrypto, this.logger, undefined, this.performanceClient);
112
+ // Initialize the token cache
113
+ this.tokenCache = new TokenCache(this.config, this.browserStorage, this.logger, this.browserCrypto);
114
+ this.activeSilentTokenRequests = new Map();
115
+ // Register listener functions
116
+ this.trackPageVisibility = this.trackPageVisibility.bind(this);
117
+ // Register listener functions
118
+ this.trackPageVisibilityWithMeasurement =
119
+ this.trackPageVisibilityWithMeasurement.bind(this);
120
+ }
121
+ static async createController(operatingContext, request) {
122
+ const controller = new StandardController(operatingContext);
123
+ await controller.initialize(request);
124
+ return controller;
125
+ }
126
+ trackPageVisibility(correlationId) {
127
+ if (!correlationId) {
128
+ return;
129
+ }
130
+ this.logger.info("Perf: Visibility change detected");
131
+ this.performanceClient.incrementFields({ visibilityChangeCount: 1 }, correlationId);
132
+ }
133
+ /**
134
+ * Initializer function to perform async startup tasks such as connecting to WAM extension
135
+ * @param request {?InitializeApplicationRequest} correlation id
136
+ */
137
+ async initialize(request) {
138
+ this.logger.trace("initialize called");
139
+ if (this.initialized) {
140
+ this.logger.info("initialize has already been called, exiting early.");
141
+ return;
142
+ }
143
+ const initCorrelationId = request?.correlationId || this.getRequestCorrelationId();
144
+ const allowNativeBroker = this.config.system.allowNativeBroker;
145
+ const initMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.InitializeClientApplication, initCorrelationId);
146
+ this.eventHandler.emitEvent(EventType.INITIALIZE_START);
147
+ if (allowNativeBroker) {
148
+ try {
149
+ this.nativeExtensionProvider =
150
+ await NativeMessageHandler.createProvider(this.logger, this.config.system.nativeBrokerHandshakeTimeout, this.performanceClient);
151
+ }
152
+ catch (e) {
153
+ this.logger.verbose(e);
154
+ }
155
+ }
156
+ if (!this.config.cache.claimsBasedCachingEnabled) {
157
+ this.logger.verbose("Claims-based caching is disabled. Clearing the previous cache with claims");
158
+ await invokeAsync(this.browserStorage.clearTokensAndKeysWithClaims.bind(this.browserStorage), PerformanceEvents.ClearTokensAndKeysWithClaims, this.logger, this.performanceClient, initCorrelationId)(this.performanceClient, initCorrelationId);
159
+ }
160
+ this.initialized = true;
161
+ this.eventHandler.emitEvent(EventType.INITIALIZE_END);
162
+ initMeasurement.end({ allowNativeBroker, success: true });
163
+ }
164
+ // #region Redirect Flow
165
+ /**
166
+ * Event handler function which allows users to fire events after the PublicClientApplication object
167
+ * has loaded during redirect flows. This should be invoked on all page loads involved in redirect
168
+ * auth flows.
169
+ * @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.
170
+ * @returns Token response or null. If the return value is null, then no auth redirect was detected.
171
+ */
172
+ async handleRedirectPromise(hash) {
173
+ this.logger.verbose("handleRedirectPromise called");
174
+ // Block token acquisition before initialize has been called
175
+ blockAPICallsBeforeInitialize(this.initialized);
176
+ if (this.isBrowserEnvironment) {
177
+ /**
178
+ * Store the promise on the PublicClientApplication instance if this is the first invocation of handleRedirectPromise,
179
+ * otherwise return the promise from the first invocation. Prevents race conditions when handleRedirectPromise is called
180
+ * several times concurrently.
181
+ */
182
+ const redirectResponseKey = hash || "";
183
+ let response = this.redirectResponse.get(redirectResponseKey);
184
+ if (typeof response === "undefined") {
185
+ response = this.handleRedirectPromiseInternal(hash);
186
+ this.redirectResponse.set(redirectResponseKey, response);
187
+ this.logger.verbose("handleRedirectPromise has been called for the first time, storing the promise");
188
+ }
189
+ else {
190
+ this.logger.verbose("handleRedirectPromise has been called previously, returning the result from the first call");
191
+ }
192
+ return response;
193
+ }
194
+ this.logger.verbose("handleRedirectPromise returns null, not browser environment");
195
+ return null;
196
+ }
197
+ /**
198
+ * The internal details of handleRedirectPromise. This is separated out to a helper to allow handleRedirectPromise to memoize requests
199
+ * @param hash
200
+ * @returns
201
+ */
202
+ async handleRedirectPromiseInternal(hash) {
203
+ const loggedInAccounts = this.getAllAccounts();
204
+ const request = this.browserStorage.getCachedNativeRequest();
205
+ const useNative = request &&
206
+ NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeExtensionProvider) &&
207
+ this.nativeExtensionProvider &&
208
+ !hash;
209
+ const correlationId = useNative
210
+ ? request?.correlationId
211
+ : this.browserStorage.getTemporaryCache(TemporaryCacheKeys.CORRELATION_ID, true) || "";
212
+ const rootMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenRedirect, correlationId);
213
+ this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, InteractionType.Redirect);
214
+ let redirectResponse;
215
+ if (useNative && this.nativeExtensionProvider) {
216
+ this.logger.trace("handleRedirectPromise - acquiring token from native platform");
217
+ const nativeClient = new NativeInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.handleRedirectPromise, this.performanceClient, this.nativeExtensionProvider, request.accountId, this.nativeInternalStorage, request.correlationId);
218
+ redirectResponse = invokeAsync(nativeClient.handleRedirectPromise.bind(nativeClient), PerformanceEvents.HandleNativeRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)(this.performanceClient, rootMeasurement.event.correlationId);
219
+ }
220
+ else {
221
+ this.logger.trace("handleRedirectPromise - acquiring token from web flow");
222
+ const redirectClient = this.createRedirectClient(correlationId);
223
+ redirectResponse = invokeAsync(redirectClient.handleRedirectPromise.bind(redirectClient), PerformanceEvents.HandleRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)(hash, rootMeasurement);
224
+ }
225
+ return redirectResponse
226
+ .then((result) => {
227
+ if (result) {
228
+ // Emit login event if number of accounts change
229
+ const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
230
+ if (isLoggingIn) {
231
+ this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, InteractionType.Redirect, result);
232
+ this.logger.verbose("handleRedirectResponse returned result, login success");
233
+ }
234
+ else {
235
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, InteractionType.Redirect, result);
236
+ this.logger.verbose("handleRedirectResponse returned result, acquire token success");
237
+ }
238
+ rootMeasurement.end({
239
+ success: true,
240
+ accountType: getAccountType(result.account),
241
+ });
242
+ }
243
+ else {
244
+ /*
245
+ * Instrument an event only if an error code is set. Otherwise, discard it when the redirect response
246
+ * is empty and the error code is missing.
247
+ */
248
+ if (rootMeasurement.event.errorCode) {
249
+ rootMeasurement.end({ success: false });
250
+ }
251
+ else {
252
+ rootMeasurement.discard();
253
+ }
254
+ }
255
+ this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, InteractionType.Redirect);
256
+ return result;
257
+ })
258
+ .catch((e) => {
259
+ const eventError = e;
260
+ // Emit login event if there is an account
261
+ if (loggedInAccounts.length > 0) {
262
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, InteractionType.Redirect, null, eventError);
263
+ }
264
+ else {
265
+ this.eventHandler.emitEvent(EventType.LOGIN_FAILURE, InteractionType.Redirect, null, eventError);
266
+ }
267
+ this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, InteractionType.Redirect);
268
+ rootMeasurement.end({
269
+ success: false,
270
+ }, eventError);
271
+ throw e;
272
+ });
273
+ }
274
+ /**
275
+ * 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
276
+ * the page, so any code that follows this function will not execute.
277
+ *
278
+ * 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
279
+ * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
280
+ *
281
+ * @param request
282
+ */
283
+ async acquireTokenRedirect(request) {
284
+ // Preflight request
285
+ const correlationId = this.getRequestCorrelationId(request);
286
+ this.logger.verbose("acquireTokenRedirect called", correlationId);
287
+ const atrMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenPreRedirect, correlationId);
288
+ atrMeasurement.add({
289
+ accountType: getAccountType(request.account),
290
+ scenarioId: request.scenarioId,
291
+ });
292
+ // Override on request only if set, as onRedirectNavigate field is deprecated
293
+ const onRedirectNavigateCb = request.onRedirectNavigate;
294
+ if (onRedirectNavigateCb) {
295
+ request.onRedirectNavigate = (url) => {
296
+ const navigate = typeof onRedirectNavigateCb === "function"
297
+ ? onRedirectNavigateCb(url)
298
+ : undefined;
299
+ if (navigate !== false) {
300
+ atrMeasurement.end({ success: true });
301
+ }
302
+ else {
303
+ atrMeasurement.discard();
304
+ }
305
+ return navigate;
306
+ };
307
+ }
308
+ else {
309
+ const configOnRedirectNavigateCb = this.config.auth.onRedirectNavigate;
310
+ this.config.auth.onRedirectNavigate = (url) => {
311
+ const navigate = typeof configOnRedirectNavigateCb === "function"
312
+ ? configOnRedirectNavigateCb(url)
313
+ : undefined;
314
+ if (navigate !== false) {
315
+ atrMeasurement.end({ success: true });
316
+ }
317
+ else {
318
+ atrMeasurement.discard();
319
+ }
320
+ return navigate;
321
+ };
322
+ }
323
+ // If logged in, emit acquire token events
324
+ const isLoggedIn = this.getAllAccounts().length > 0;
325
+ try {
326
+ redirectPreflightCheck(this.initialized, this.config);
327
+ this.browserStorage.setInteractionInProgress(true);
328
+ if (isLoggedIn) {
329
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, InteractionType.Redirect, request);
330
+ }
331
+ else {
332
+ this.eventHandler.emitEvent(EventType.LOGIN_START, InteractionType.Redirect, request);
333
+ }
334
+ let result;
335
+ if (this.nativeExtensionProvider && this.canUseNative(request)) {
336
+ 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);
337
+ result = nativeClient
338
+ .acquireTokenRedirect(request, atrMeasurement)
339
+ .catch((e) => {
340
+ if (e instanceof NativeAuthError &&
341
+ isFatalNativeAuthError(e)) {
342
+ this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
343
+ const redirectClient = this.createRedirectClient(correlationId);
344
+ return redirectClient.acquireToken(request);
345
+ }
346
+ else if (e instanceof InteractionRequiredAuthError) {
347
+ this.logger.verbose("acquireTokenRedirect - Resolving interaction required error thrown by native broker by falling back to web flow");
348
+ const redirectClient = this.createRedirectClient(correlationId);
349
+ return redirectClient.acquireToken(request);
350
+ }
351
+ this.browserStorage.setInteractionInProgress(false);
352
+ throw e;
353
+ });
354
+ }
355
+ else {
356
+ const redirectClient = this.createRedirectClient(correlationId);
357
+ result = redirectClient.acquireToken(request);
358
+ }
359
+ return await result;
360
+ }
361
+ catch (e) {
362
+ atrMeasurement.end({ success: false }, e);
363
+ if (isLoggedIn) {
364
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, InteractionType.Redirect, null, e);
365
+ }
366
+ else {
367
+ this.eventHandler.emitEvent(EventType.LOGIN_FAILURE, InteractionType.Redirect, null, e);
368
+ }
369
+ throw e;
370
+ }
371
+ }
372
+ // #endregion
373
+ // #region Popup Flow
374
+ /**
375
+ * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
376
+ *
377
+ * @param request
378
+ *
379
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
380
+ */
381
+ acquireTokenPopup(request) {
382
+ const correlationId = this.getRequestCorrelationId(request);
383
+ const atPopupMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenPopup, correlationId);
384
+ atPopupMeasurement.add({
385
+ scenarioId: request.scenarioId,
386
+ accountType: getAccountType(request.account),
387
+ });
388
+ try {
389
+ this.logger.verbose("acquireTokenPopup called", correlationId);
390
+ preflightCheck(this.initialized, atPopupMeasurement);
391
+ this.browserStorage.setInteractionInProgress(true);
392
+ }
393
+ catch (e) {
394
+ // Since this function is syncronous we need to reject
395
+ return Promise.reject(e);
396
+ }
397
+ // If logged in, emit acquire token events
398
+ const loggedInAccounts = this.getAllAccounts();
399
+ if (loggedInAccounts.length > 0) {
400
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, InteractionType.Popup, request);
401
+ }
402
+ else {
403
+ this.eventHandler.emitEvent(EventType.LOGIN_START, InteractionType.Popup, request);
404
+ }
405
+ let result;
406
+ if (this.canUseNative(request)) {
407
+ result = this.acquireTokenNative({
408
+ ...request,
409
+ correlationId,
410
+ }, ApiId.acquireTokenPopup)
411
+ .then((response) => {
412
+ this.browserStorage.setInteractionInProgress(false);
413
+ atPopupMeasurement.end({
414
+ success: true,
415
+ isNativeBroker: true,
416
+ requestId: response.requestId,
417
+ accountType: getAccountType(response.account),
418
+ });
419
+ return response;
420
+ })
421
+ .catch((e) => {
422
+ if (e instanceof NativeAuthError &&
423
+ isFatalNativeAuthError(e)) {
424
+ this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
425
+ const popupClient = this.createPopupClient(correlationId);
426
+ return popupClient.acquireToken(request);
427
+ }
428
+ else if (e instanceof InteractionRequiredAuthError) {
429
+ this.logger.verbose("acquireTokenPopup - Resolving interaction required error thrown by native broker by falling back to web flow");
430
+ const popupClient = this.createPopupClient(correlationId);
431
+ return popupClient.acquireToken(request);
432
+ }
433
+ this.browserStorage.setInteractionInProgress(false);
434
+ throw e;
435
+ });
436
+ }
437
+ else {
438
+ const popupClient = this.createPopupClient(correlationId);
439
+ result = popupClient.acquireToken(request);
440
+ }
441
+ return result
442
+ .then((result) => {
443
+ /*
444
+ * If logged in, emit acquire token events
445
+ */
446
+ const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
447
+ if (isLoggingIn) {
448
+ this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, InteractionType.Popup, result);
449
+ }
450
+ else {
451
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, InteractionType.Popup, result);
452
+ }
453
+ atPopupMeasurement.end({
454
+ success: true,
455
+ requestId: result.requestId,
456
+ accessTokenSize: result.accessToken.length,
457
+ idTokenSize: result.idToken.length,
458
+ accountType: getAccountType(result.account),
459
+ });
460
+ return result;
461
+ })
462
+ .catch((e) => {
463
+ if (loggedInAccounts.length > 0) {
464
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, InteractionType.Popup, null, e);
465
+ }
466
+ else {
467
+ this.eventHandler.emitEvent(EventType.LOGIN_FAILURE, InteractionType.Popup, null, e);
468
+ }
469
+ atPopupMeasurement.end({
470
+ success: false,
471
+ }, e);
472
+ // Since this function is syncronous we need to reject
473
+ return Promise.reject(e);
474
+ });
475
+ }
476
+ trackPageVisibilityWithMeasurement() {
477
+ const measurement = this.ssoSilentMeasurement ||
478
+ this.acquireTokenByCodeAsyncMeasurement;
479
+ if (!measurement) {
480
+ return;
481
+ }
482
+ this.logger.info("Perf: Visibility change detected in ", measurement.event.name);
483
+ measurement.increment({
484
+ visibilityChangeCount: 1,
485
+ });
486
+ }
487
+ // #endregion
488
+ // #region Silent Flow
489
+ /**
490
+ * This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
491
+ * - Any browser using a form of Intelligent Tracking Prevention
492
+ * - If there is not an established session with the service
493
+ *
494
+ * In these cases, the request must be done inside a popup or full frame redirect.
495
+ *
496
+ * For the cases where interaction is required, you cannot send a request with prompt=none.
497
+ *
498
+ * If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
499
+ * you session on the server still exists.
500
+ * @param request {@link SsoSilentRequest}
501
+ *
502
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
503
+ */
504
+ async ssoSilent(request) {
505
+ const correlationId = this.getRequestCorrelationId(request);
506
+ const validRequest = {
507
+ ...request,
508
+ // will be PromptValue.NONE or PromptValue.NO_SESSION
509
+ prompt: request.prompt,
510
+ correlationId: correlationId,
511
+ };
512
+ this.ssoSilentMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.SsoSilent, correlationId);
513
+ this.ssoSilentMeasurement?.add({
514
+ scenarioId: request.scenarioId,
515
+ accountType: getAccountType(request.account),
516
+ });
517
+ preflightCheck(this.initialized, this.ssoSilentMeasurement);
518
+ this.ssoSilentMeasurement?.increment({
519
+ visibilityChangeCount: 0,
520
+ });
521
+ document.addEventListener("visibilitychange", this.trackPageVisibilityWithMeasurement);
522
+ this.logger.verbose("ssoSilent called", correlationId);
523
+ this.eventHandler.emitEvent(EventType.SSO_SILENT_START, InteractionType.Silent, validRequest);
524
+ let result;
525
+ if (this.canUseNative(validRequest)) {
526
+ result = this.acquireTokenNative(validRequest, ApiId.ssoSilent).catch((e) => {
527
+ // If native token acquisition fails for availability reasons fallback to standard flow
528
+ if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
529
+ this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
530
+ const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
531
+ return silentIframeClient.acquireToken(validRequest);
532
+ }
533
+ throw e;
534
+ });
535
+ }
536
+ else {
537
+ const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
538
+ result = silentIframeClient.acquireToken(validRequest);
539
+ }
540
+ return result
541
+ .then((response) => {
542
+ this.eventHandler.emitEvent(EventType.SSO_SILENT_SUCCESS, InteractionType.Silent, response);
543
+ this.ssoSilentMeasurement?.end({
544
+ success: true,
545
+ isNativeBroker: response.fromNativeBroker,
546
+ requestId: response.requestId,
547
+ accessTokenSize: response.accessToken.length,
548
+ idTokenSize: response.idToken.length,
549
+ accountType: getAccountType(response.account),
550
+ });
551
+ return response;
552
+ })
553
+ .catch((e) => {
554
+ this.eventHandler.emitEvent(EventType.SSO_SILENT_FAILURE, InteractionType.Silent, null, e);
555
+ this.ssoSilentMeasurement?.end({
556
+ success: false,
557
+ }, e);
558
+ throw e;
559
+ })
560
+ .finally(() => {
561
+ document.removeEventListener("visibilitychange", this.trackPageVisibilityWithMeasurement);
562
+ });
563
+ }
564
+ /**
565
+ * This function redeems an authorization code (passed as code) from the eSTS token endpoint.
566
+ * This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
567
+ * This API is not indended for normal authorization code acquisition and redemption.
568
+ *
569
+ * Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
570
+ *
571
+ * @param request {@link AuthorizationCodeRequest}
572
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
573
+ */
574
+ async acquireTokenByCode(request) {
575
+ const correlationId = this.getRequestCorrelationId(request);
576
+ this.logger.trace("acquireTokenByCode called", correlationId);
577
+ const atbcMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenByCode, correlationId);
578
+ preflightCheck(this.initialized, atbcMeasurement);
579
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_BY_CODE_START, InteractionType.Silent, request);
580
+ atbcMeasurement.add({ scenarioId: request.scenarioId });
581
+ try {
582
+ if (request.code && request.nativeAccountId) {
583
+ // Throw error in case server returns both spa_code and spa_accountid in exchange for auth code.
584
+ throw createBrowserAuthError(spaCodeAndNativeAccountIdPresent);
585
+ }
586
+ else if (request.code) {
587
+ const hybridAuthCode = request.code;
588
+ let response = this.hybridAuthCodeResponses.get(hybridAuthCode);
589
+ if (!response) {
590
+ this.logger.verbose("Initiating new acquireTokenByCode request", correlationId);
591
+ response = this.acquireTokenByCodeAsync({
592
+ ...request,
593
+ correlationId,
594
+ })
595
+ .then((result) => {
596
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_BY_CODE_SUCCESS, InteractionType.Silent, result);
597
+ this.hybridAuthCodeResponses.delete(hybridAuthCode);
598
+ atbcMeasurement.end({
599
+ success: true,
600
+ isNativeBroker: result.fromNativeBroker,
601
+ requestId: result.requestId,
602
+ accessTokenSize: result.accessToken.length,
603
+ idTokenSize: result.idToken.length,
604
+ accountType: getAccountType(result.account),
605
+ });
606
+ return result;
607
+ })
608
+ .catch((error) => {
609
+ this.hybridAuthCodeResponses.delete(hybridAuthCode);
610
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_BY_CODE_FAILURE, InteractionType.Silent, null, error);
611
+ atbcMeasurement.end({
612
+ success: false,
613
+ }, error);
614
+ throw error;
615
+ });
616
+ this.hybridAuthCodeResponses.set(hybridAuthCode, response);
617
+ }
618
+ else {
619
+ this.logger.verbose("Existing acquireTokenByCode request found", correlationId);
620
+ atbcMeasurement.discard();
621
+ }
622
+ return await response;
623
+ }
624
+ else if (request.nativeAccountId) {
625
+ if (this.canUseNative(request, request.nativeAccountId)) {
626
+ const result = await this.acquireTokenNative({
627
+ ...request,
628
+ correlationId,
629
+ }, ApiId.acquireTokenByCode, request.nativeAccountId).catch((e) => {
630
+ // If native token acquisition fails for availability reasons fallback to standard flow
631
+ if (e instanceof NativeAuthError &&
632
+ isFatalNativeAuthError(e)) {
633
+ this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
634
+ }
635
+ throw e;
636
+ });
637
+ atbcMeasurement.end({
638
+ accountType: getAccountType(result.account),
639
+ success: true,
640
+ });
641
+ return result;
642
+ }
643
+ else {
644
+ throw createBrowserAuthError(unableToAcquireTokenFromNativePlatform);
645
+ }
646
+ }
647
+ else {
648
+ throw createBrowserAuthError(authCodeOrNativeAccountIdRequired);
649
+ }
650
+ }
651
+ catch (e) {
652
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_BY_CODE_FAILURE, InteractionType.Silent, null, e);
653
+ atbcMeasurement.end({
654
+ success: false,
655
+ }, e);
656
+ throw e;
657
+ }
658
+ }
659
+ /**
660
+ * Creates a SilentAuthCodeClient to redeem an authorization code.
661
+ * @param request
662
+ * @returns Result of the operation to redeem the authorization code
663
+ */
664
+ async acquireTokenByCodeAsync(request) {
665
+ this.logger.trace("acquireTokenByCodeAsync called", request.correlationId);
666
+ this.acquireTokenByCodeAsyncMeasurement =
667
+ this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenByCodeAsync, request.correlationId);
668
+ this.acquireTokenByCodeAsyncMeasurement?.increment({
669
+ visibilityChangeCount: 0,
670
+ });
671
+ document.addEventListener("visibilitychange", this.trackPageVisibilityWithMeasurement);
672
+ const silentAuthCodeClient = this.createSilentAuthCodeClient(request.correlationId);
673
+ const silentTokenResult = await silentAuthCodeClient
674
+ .acquireToken(request)
675
+ .then((response) => {
676
+ this.acquireTokenByCodeAsyncMeasurement?.end({
677
+ success: true,
678
+ fromCache: response.fromCache,
679
+ isNativeBroker: response.fromNativeBroker,
680
+ requestId: response.requestId,
681
+ });
682
+ return response;
683
+ })
684
+ .catch((tokenRenewalError) => {
685
+ this.acquireTokenByCodeAsyncMeasurement?.end({
686
+ success: false,
687
+ }, tokenRenewalError);
688
+ throw tokenRenewalError;
689
+ })
690
+ .finally(() => {
691
+ document.removeEventListener("visibilitychange", this.trackPageVisibilityWithMeasurement);
692
+ });
693
+ return silentTokenResult;
694
+ }
695
+ /**
696
+ * Attempt to acquire an access token from the cache
697
+ * @param silentCacheClient SilentCacheClient
698
+ * @param commonRequest CommonSilentFlowRequest
699
+ * @param silentRequest SilentRequest
700
+ * @returns A promise that, when resolved, returns the access token
701
+ */
702
+ async acquireTokenFromCache(commonRequest, cacheLookupPolicy) {
703
+ this.performanceClient.addQueueMeasurement(PerformanceEvents.AcquireTokenFromCache, commonRequest.correlationId);
704
+ switch (cacheLookupPolicy) {
705
+ case CacheLookupPolicy.Default:
706
+ case CacheLookupPolicy.AccessToken:
707
+ case CacheLookupPolicy.AccessTokenAndRefreshToken:
708
+ const silentCacheClient = this.createSilentCacheClient(commonRequest.correlationId);
709
+ return invokeAsync(silentCacheClient.acquireToken.bind(silentCacheClient), PerformanceEvents.SilentCacheClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
710
+ default:
711
+ throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
712
+ }
713
+ }
714
+ /**
715
+ * Attempt to acquire an access token via a refresh token
716
+ * @param commonRequest CommonSilentFlowRequest
717
+ * @param cacheLookupPolicy CacheLookupPolicy
718
+ * @returns A promise that, when resolved, returns the access token
719
+ */
720
+ async acquireTokenByRefreshToken(commonRequest, cacheLookupPolicy) {
721
+ this.performanceClient.addQueueMeasurement(PerformanceEvents.AcquireTokenByRefreshToken, commonRequest.correlationId);
722
+ switch (cacheLookupPolicy) {
723
+ case CacheLookupPolicy.Default:
724
+ case CacheLookupPolicy.AccessTokenAndRefreshToken:
725
+ case CacheLookupPolicy.RefreshToken:
726
+ case CacheLookupPolicy.RefreshTokenAndNetwork:
727
+ const silentRefreshClient = this.createSilentRefreshClient(commonRequest.correlationId);
728
+ return invokeAsync(silentRefreshClient.acquireToken.bind(silentRefreshClient), PerformanceEvents.SilentRefreshClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
729
+ default:
730
+ throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
731
+ }
732
+ }
733
+ /**
734
+ * Attempt to acquire an access token via an iframe
735
+ * @param request CommonSilentFlowRequest
736
+ * @returns A promise that, when resolved, returns the access token
737
+ */
738
+ async acquireTokenBySilentIframe(request) {
739
+ this.performanceClient.addQueueMeasurement(PerformanceEvents.AcquireTokenBySilentIframe, request.correlationId);
740
+ const silentIframeClient = this.createSilentIframeClient(request.correlationId);
741
+ return invokeAsync(silentIframeClient.acquireToken.bind(silentIframeClient), PerformanceEvents.SilentIframeClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(request);
742
+ }
743
+ // #endregion
744
+ // #region Logout
745
+ /**
746
+ * Deprecated logout function. Use logoutRedirect or logoutPopup instead
747
+ * @param logoutRequest
748
+ * @deprecated
749
+ */
750
+ async logout(logoutRequest) {
751
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
752
+ this.logger.warning("logout API is deprecated and will be removed in msal-browser v3.0.0. Use logoutRedirect instead.", correlationId);
753
+ return this.logoutRedirect({
754
+ correlationId,
755
+ ...logoutRequest,
756
+ });
757
+ }
758
+ /**
759
+ * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
760
+ * Default behaviour is to redirect the user to `window.location.href`.
761
+ * @param logoutRequest
762
+ */
763
+ async logoutRedirect(logoutRequest) {
764
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
765
+ redirectPreflightCheck(this.initialized, this.config);
766
+ this.browserStorage.setInteractionInProgress(true);
767
+ const redirectClient = this.createRedirectClient(correlationId);
768
+ return redirectClient.logout(logoutRequest);
769
+ }
770
+ /**
771
+ * Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
772
+ * @param logoutRequest
773
+ */
774
+ logoutPopup(logoutRequest) {
775
+ try {
776
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
777
+ preflightCheck$1(this.initialized);
778
+ this.browserStorage.setInteractionInProgress(true);
779
+ const popupClient = this.createPopupClient(correlationId);
780
+ return popupClient.logout(logoutRequest);
781
+ }
782
+ catch (e) {
783
+ // Since this function is syncronous we need to reject
784
+ return Promise.reject(e);
785
+ }
786
+ }
787
+ /**
788
+ * Creates a cache interaction client to clear broswer cache.
789
+ * @param logoutRequest
790
+ */
791
+ async clearCache(logoutRequest) {
792
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
793
+ const cacheClient = this.createSilentCacheClient(correlationId);
794
+ return cacheClient.logout(logoutRequest);
795
+ }
796
+ // #endregion
797
+ // #region Account APIs
798
+ /**
799
+ * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
800
+ * @param accountFilter - (Optional) filter to narrow down the accounts returned
801
+ * @returns Array of AccountInfo objects in cache
802
+ */
803
+ getAllAccounts(accountFilter) {
804
+ return getAllAccounts(this.logger, this.browserStorage, this.isBrowserEnvironment, accountFilter);
805
+ }
806
+ /**
807
+ * Returns the first account found in the cache that matches the account filter passed in.
808
+ * @param accountFilter
809
+ * @returns The first account found in the cache matching the provided filter or null if no account could be found.
810
+ */
811
+ getAccount(accountFilter) {
812
+ return getAccount(accountFilter, this.logger, this.browserStorage);
813
+ }
814
+ /**
815
+ * Returns the signed in account matching username.
816
+ * (the account object is created at the time of successful login)
817
+ * or null when no matching account is found.
818
+ * This API is provided for convenience but getAccountById should be used for best reliability
819
+ * @param username
820
+ * @returns The account object stored in MSAL
821
+ */
822
+ getAccountByUsername(username) {
823
+ return getAccountByUsername(username, this.logger, this.browserStorage);
824
+ }
825
+ /**
826
+ * Returns the signed in account matching homeAccountId.
827
+ * (the account object is created at the time of successful login)
828
+ * or null when no matching account is found
829
+ * @param homeAccountId
830
+ * @returns The account object stored in MSAL
831
+ */
832
+ getAccountByHomeId(homeAccountId) {
833
+ return getAccountByHomeId(homeAccountId, this.logger, this.browserStorage);
834
+ }
835
+ /**
836
+ * Returns the signed in account matching localAccountId.
837
+ * (the account object is created at the time of successful login)
838
+ * or null when no matching account is found
839
+ * @param localAccountId
840
+ * @returns The account object stored in MSAL
841
+ */
842
+ getAccountByLocalId(localAccountId) {
843
+ return getAccountByLocalId(localAccountId, this.logger, this.browserStorage);
844
+ }
845
+ /**
846
+ * Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
847
+ * @param account
848
+ */
849
+ setActiveAccount(account) {
850
+ setActiveAccount(account, this.browserStorage);
851
+ }
852
+ /**
853
+ * Gets the currently active account
854
+ */
855
+ getActiveAccount() {
856
+ return getActiveAccount(this.browserStorage);
857
+ }
858
+ // #endregion
859
+ /**
860
+ * Hydrates the cache with the tokens from an AuthenticationResult
861
+ * @param result
862
+ * @param request
863
+ * @returns
864
+ */
865
+ async hydrateCache(result, request) {
866
+ this.logger.verbose("hydrateCache called");
867
+ // Account gets saved to browser storage regardless of native or not
868
+ const accountEntity = AccountEntity.createFromAccountInfo(result.account, result.cloudGraphHostName, result.msGraphHost);
869
+ this.browserStorage.setAccount(accountEntity);
870
+ if (result.fromNativeBroker) {
871
+ this.logger.verbose("Response was from native broker, storing in-memory");
872
+ // Tokens from native broker are stored in-memory
873
+ return this.nativeInternalStorage.hydrateCache(result, request);
874
+ }
875
+ else {
876
+ return this.browserStorage.hydrateCache(result, request);
877
+ }
878
+ }
879
+ // #region Helpers
880
+ /**
881
+ * Acquire a token from native device (e.g. WAM)
882
+ * @param request
883
+ */
884
+ async acquireTokenNative(request, apiId, accountId) {
885
+ this.logger.trace("acquireTokenNative called");
886
+ if (!this.nativeExtensionProvider) {
887
+ throw createBrowserAuthError(nativeConnectionNotEstablished);
888
+ }
889
+ const nativeClient = new NativeInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, apiId, this.performanceClient, this.nativeExtensionProvider, accountId || this.getNativeAccountId(request), this.nativeInternalStorage, request.correlationId);
890
+ return nativeClient.acquireToken(request);
891
+ }
892
+ /**
893
+ * Returns boolean indicating if this request can use the native broker
894
+ * @param request
895
+ */
896
+ canUseNative(request, accountId) {
897
+ this.logger.trace("canUseNative called");
898
+ if (!NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeExtensionProvider, request.authenticationScheme)) {
899
+ this.logger.trace("canUseNative: isNativeAvailable returned false, returning false");
900
+ return false;
901
+ }
902
+ if (request.prompt) {
903
+ switch (request.prompt) {
904
+ case PromptValue.NONE:
905
+ case PromptValue.CONSENT:
906
+ case PromptValue.LOGIN:
907
+ this.logger.trace("canUseNative: prompt is compatible with native flow");
908
+ break;
909
+ default:
910
+ this.logger.trace(`canUseNative: prompt = ${request.prompt} is not compatible with native flow, returning false`);
911
+ return false;
912
+ }
913
+ }
914
+ if (!accountId && !this.getNativeAccountId(request)) {
915
+ this.logger.trace("canUseNative: nativeAccountId is not available, returning false");
916
+ return false;
917
+ }
918
+ return true;
919
+ }
920
+ /**
921
+ * Get the native accountId from the account
922
+ * @param request
923
+ * @returns
924
+ */
925
+ getNativeAccountId(request) {
926
+ const account = request.account ||
927
+ this.getAccount({
928
+ loginHint: request.loginHint,
929
+ sid: request.sid,
930
+ }) ||
931
+ this.getActiveAccount();
932
+ return (account && account.nativeAccountId) || "";
933
+ }
934
+ /**
935
+ * Returns new instance of the Popup Interaction Client
936
+ * @param correlationId
937
+ */
938
+ createPopupClient(correlationId) {
939
+ return new PopupClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, this.nativeExtensionProvider, correlationId);
940
+ }
941
+ /**
942
+ * Returns new instance of the Redirect Interaction Client
943
+ * @param correlationId
944
+ */
945
+ createRedirectClient(correlationId) {
946
+ return new RedirectClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, this.nativeExtensionProvider, correlationId);
947
+ }
948
+ /**
949
+ * Returns new instance of the Silent Iframe Interaction Client
950
+ * @param correlationId
951
+ */
952
+ createSilentIframeClient(correlationId) {
953
+ return new SilentIframeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.ssoSilent, this.performanceClient, this.nativeInternalStorage, this.nativeExtensionProvider, correlationId);
954
+ }
955
+ /**
956
+ * Returns new instance of the Silent Cache Interaction Client
957
+ */
958
+ createSilentCacheClient(correlationId) {
959
+ return new SilentCacheClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeExtensionProvider, correlationId);
960
+ }
961
+ /**
962
+ * Returns new instance of the Silent Refresh Interaction Client
963
+ */
964
+ createSilentRefreshClient(correlationId) {
965
+ return new SilentRefreshClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeExtensionProvider, correlationId);
966
+ }
967
+ /**
968
+ * Returns new instance of the Silent AuthCode Interaction Client
969
+ */
970
+ createSilentAuthCodeClient(correlationId) {
971
+ return new SilentAuthCodeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenByCode, this.performanceClient, this.nativeExtensionProvider, correlationId);
972
+ }
973
+ /**
974
+ * Adds event callbacks to array
975
+ * @param callback
976
+ */
977
+ addEventCallback(callback) {
978
+ return this.eventHandler.addEventCallback(callback);
979
+ }
980
+ /**
981
+ * Removes callback with provided id from callback array
982
+ * @param callbackId
983
+ */
984
+ removeEventCallback(callbackId) {
985
+ this.eventHandler.removeEventCallback(callbackId);
986
+ }
987
+ /**
988
+ * Registers a callback to receive performance events.
989
+ *
990
+ * @param {PerformanceCallbackFunction} callback
991
+ * @returns {string}
992
+ */
993
+ addPerformanceCallback(callback) {
994
+ return this.performanceClient.addPerformanceCallback(callback);
995
+ }
996
+ /**
997
+ * Removes a callback registered with addPerformanceCallback.
998
+ *
999
+ * @param {string} callbackId
1000
+ * @returns {boolean}
1001
+ */
1002
+ removePerformanceCallback(callbackId) {
1003
+ return this.performanceClient.removePerformanceCallback(callbackId);
1004
+ }
1005
+ /**
1006
+ * Adds event listener that emits an event when a user account is added or removed from localstorage in a different browser tab or window
1007
+ */
1008
+ enableAccountStorageEvents() {
1009
+ this.eventHandler.enableAccountStorageEvents();
1010
+ }
1011
+ /**
1012
+ * Removes event listener that emits an event when a user account is added or removed from localstorage in a different browser tab or window
1013
+ */
1014
+ disableAccountStorageEvents() {
1015
+ this.eventHandler.disableAccountStorageEvents();
1016
+ }
1017
+ /**
1018
+ * Gets the token cache for the application.
1019
+ */
1020
+ getTokenCache() {
1021
+ return this.tokenCache;
1022
+ }
1023
+ /**
1024
+ * Returns the logger instance
1025
+ */
1026
+ getLogger() {
1027
+ return this.logger;
1028
+ }
1029
+ /**
1030
+ * Replaces the default logger set in configurations with new Logger with new configurations
1031
+ * @param logger Logger instance
1032
+ */
1033
+ setLogger(logger) {
1034
+ this.logger = logger;
1035
+ }
1036
+ /**
1037
+ * Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
1038
+ * @param sku
1039
+ * @param version
1040
+ */
1041
+ initializeWrapperLibrary(sku, version) {
1042
+ // Validate the SKU passed in is one we expect
1043
+ this.browserStorage.setWrapperMetadata(sku, version);
1044
+ }
1045
+ /**
1046
+ * Sets navigation client
1047
+ * @param navigationClient
1048
+ */
1049
+ setNavigationClient(navigationClient) {
1050
+ this.navigationClient = navigationClient;
1051
+ }
1052
+ /**
1053
+ * Returns the configuration object
1054
+ */
1055
+ getConfiguration() {
1056
+ return this.config;
1057
+ }
1058
+ /**
1059
+ * Returns the performance client
1060
+ */
1061
+ getPerformanceClient() {
1062
+ return this.performanceClient;
1063
+ }
1064
+ /**
1065
+ * Returns the browser env indicator
1066
+ */
1067
+ isBrowserEnv() {
1068
+ return this.isBrowserEnvironment;
1069
+ }
1070
+ /**
1071
+ * Returns the event handler
1072
+ */
1073
+ getEventHandler() {
1074
+ return this.eventHandler;
1075
+ }
1076
+ /**
1077
+ * Generates a correlation id for a request if none is provided.
1078
+ *
1079
+ * @protected
1080
+ * @param {?Partial<BaseAuthRequest>} [request]
1081
+ * @returns {string}
1082
+ */
1083
+ getRequestCorrelationId(request) {
1084
+ if (request?.correlationId) {
1085
+ return request.correlationId;
1086
+ }
1087
+ if (this.isBrowserEnvironment) {
1088
+ return createNewGuid();
1089
+ }
1090
+ /*
1091
+ * Included for fallback for non-browser environments,
1092
+ * and to ensure this method always returns a string.
1093
+ */
1094
+ return Constants.EMPTY_STRING;
1095
+ }
1096
+ // #endregion
1097
+ /**
1098
+ * Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
1099
+ * any code that follows this function will not execute.
1100
+ *
1101
+ * 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
1102
+ * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
1103
+ *
1104
+ * @param request
1105
+ */
1106
+ async loginRedirect(request) {
1107
+ const correlationId = this.getRequestCorrelationId(request);
1108
+ this.logger.verbose("loginRedirect called", correlationId);
1109
+ return this.acquireTokenRedirect({
1110
+ correlationId,
1111
+ ...(request || DEFAULT_REQUEST),
1112
+ });
1113
+ }
1114
+ /**
1115
+ * Use when initiating the login process via opening a popup window in the user's browser
1116
+ *
1117
+ * @param request
1118
+ *
1119
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
1120
+ */
1121
+ loginPopup(request) {
1122
+ const correlationId = this.getRequestCorrelationId(request);
1123
+ this.logger.verbose("loginPopup called", correlationId);
1124
+ return this.acquireTokenPopup({
1125
+ correlationId,
1126
+ ...(request || DEFAULT_REQUEST),
1127
+ });
1128
+ }
1129
+ /**
1130
+ * Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
1131
+ *
1132
+ * @param {@link (SilentRequest:type)}
1133
+ * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
1134
+ */
1135
+ async acquireTokenSilent(request) {
1136
+ const correlationId = this.getRequestCorrelationId(request);
1137
+ const atsMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.AcquireTokenSilent, correlationId);
1138
+ atsMeasurement.add({
1139
+ cacheLookupPolicy: request.cacheLookupPolicy,
1140
+ scenarioId: request.scenarioId,
1141
+ });
1142
+ preflightCheck(this.initialized, atsMeasurement);
1143
+ this.logger.verbose("acquireTokenSilent called", correlationId);
1144
+ const account = request.account || this.getActiveAccount();
1145
+ if (!account) {
1146
+ throw createBrowserAuthError(noAccountError);
1147
+ }
1148
+ atsMeasurement.add({ accountType: getAccountType(account) });
1149
+ const thumbprint = {
1150
+ clientId: this.config.auth.clientId,
1151
+ authority: request.authority || Constants.EMPTY_STRING,
1152
+ scopes: request.scopes,
1153
+ homeAccountIdentifier: account.homeAccountId,
1154
+ claims: request.claims,
1155
+ authenticationScheme: request.authenticationScheme,
1156
+ resourceRequestMethod: request.resourceRequestMethod,
1157
+ resourceRequestUri: request.resourceRequestUri,
1158
+ shrClaims: request.shrClaims,
1159
+ sshKid: request.sshKid,
1160
+ shrOptions: request.shrOptions,
1161
+ };
1162
+ const silentRequestKey = JSON.stringify(thumbprint);
1163
+ const cachedResponse = this.activeSilentTokenRequests.get(silentRequestKey);
1164
+ if (typeof cachedResponse === "undefined") {
1165
+ this.logger.verbose("acquireTokenSilent called for the first time, storing active request", correlationId);
1166
+ const response = invokeAsync(this.acquireTokenSilentAsync.bind(this), PerformanceEvents.AcquireTokenSilentAsync, this.logger, this.performanceClient, correlationId)({
1167
+ ...request,
1168
+ correlationId,
1169
+ }, account)
1170
+ .then((result) => {
1171
+ this.activeSilentTokenRequests.delete(silentRequestKey);
1172
+ atsMeasurement.end({
1173
+ success: true,
1174
+ fromCache: result.fromCache,
1175
+ isNativeBroker: result.fromNativeBroker,
1176
+ cacheLookupPolicy: request.cacheLookupPolicy,
1177
+ requestId: result.requestId,
1178
+ accessTokenSize: result.accessToken.length,
1179
+ idTokenSize: result.idToken.length,
1180
+ });
1181
+ return result;
1182
+ })
1183
+ .catch((error) => {
1184
+ this.activeSilentTokenRequests.delete(silentRequestKey);
1185
+ atsMeasurement.end({
1186
+ success: false,
1187
+ }, error);
1188
+ throw error;
1189
+ });
1190
+ this.activeSilentTokenRequests.set(silentRequestKey, response);
1191
+ return {
1192
+ ...(await response),
1193
+ state: request.state,
1194
+ };
1195
+ }
1196
+ else {
1197
+ this.logger.verbose("acquireTokenSilent has been called previously, returning the result from the first call", correlationId);
1198
+ // Discard measurements for memoized calls, as they are usually only a couple of ms and will artificially deflate metrics
1199
+ atsMeasurement.discard();
1200
+ return {
1201
+ ...(await cachedResponse),
1202
+ state: request.state,
1203
+ };
1204
+ }
1205
+ }
1206
+ /**
1207
+ * Silently acquire an access token for a given set of scopes. Will use cached token if available, otherwise will attempt to acquire a new token from the network via refresh token.
1208
+ * @param {@link (SilentRequest:type)}
1209
+ * @param {@link (AccountInfo:type)}
1210
+ * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse}
1211
+ */
1212
+ async acquireTokenSilentAsync(request, account) {
1213
+ const trackPageVisibility = () => this.trackPageVisibility(request.correlationId);
1214
+ this.performanceClient.addQueueMeasurement(PerformanceEvents.AcquireTokenSilentAsync, request.correlationId);
1215
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, InteractionType.Silent, request);
1216
+ if (request.correlationId) {
1217
+ this.performanceClient.incrementFields({ visibilityChangeCount: 0 }, request.correlationId);
1218
+ }
1219
+ document.addEventListener("visibilitychange", trackPageVisibility);
1220
+ const silentRequest = await invokeAsync(initializeSilentRequest, PerformanceEvents.InitializeSilentRequest, this.logger, this.performanceClient, request.correlationId)(request, account, this.config, this.performanceClient, this.logger);
1221
+ const cacheLookupPolicy = request.cacheLookupPolicy || CacheLookupPolicy.Default;
1222
+ const result = this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy).catch(async (refreshTokenError) => {
1223
+ const shouldTryToResolveSilently = checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy);
1224
+ if (shouldTryToResolveSilently) {
1225
+ if (!this.activeIframeRequest) {
1226
+ let _resolve;
1227
+ // Always set the active request tracker immediately after checking it to prevent races
1228
+ this.activeIframeRequest = [
1229
+ new Promise((resolve) => {
1230
+ _resolve = resolve;
1231
+ }),
1232
+ silentRequest.correlationId,
1233
+ ];
1234
+ this.logger.verbose("Refresh token expired/invalid or CacheLookupPolicy is set to Skip, attempting acquire token by iframe.", silentRequest.correlationId);
1235
+ return invokeAsync(this.acquireTokenBySilentIframe.bind(this), PerformanceEvents.AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest)
1236
+ .then((iframeResult) => {
1237
+ _resolve(true);
1238
+ return iframeResult;
1239
+ })
1240
+ .catch((e) => {
1241
+ _resolve(false);
1242
+ throw e;
1243
+ })
1244
+ .finally(() => {
1245
+ this.activeIframeRequest = undefined;
1246
+ });
1247
+ }
1248
+ else if (cacheLookupPolicy !== CacheLookupPolicy.Skip) {
1249
+ const [activePromise, activeCorrelationId] = this.activeIframeRequest;
1250
+ this.logger.verbose(`Iframe request is already in progress, awaiting resolution for request with correlationId: ${activeCorrelationId}`, silentRequest.correlationId);
1251
+ const awaitConcurrentIframeMeasure = this.performanceClient.startMeasurement(PerformanceEvents.AwaitConcurrentIframe, silentRequest.correlationId);
1252
+ awaitConcurrentIframeMeasure.add({
1253
+ awaitIframeCorrelationId: activeCorrelationId,
1254
+ });
1255
+ const activePromiseResult = await activePromise;
1256
+ awaitConcurrentIframeMeasure.end({
1257
+ success: activePromiseResult,
1258
+ });
1259
+ if (activePromiseResult) {
1260
+ this.logger.verbose(`Parallel iframe request with correlationId: ${activeCorrelationId} succeeded. Retrying cache and/or RT redemption`, silentRequest.correlationId);
1261
+ // Retry cache lookup and/or RT exchange after iframe completes
1262
+ return this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy);
1263
+ }
1264
+ else {
1265
+ this.logger.info(`Iframe request with correlationId: ${activeCorrelationId} failed. Interaction is required.`);
1266
+ // If previous iframe request failed, it's unlikely to succeed this time. Throw original error.
1267
+ throw refreshTokenError;
1268
+ }
1269
+ }
1270
+ else {
1271
+ // Cache policy set to skip and another iframe request is already in progress
1272
+ this.logger.warning("Another iframe request is currently in progress and CacheLookupPolicy is set to Skip. This may result in degraded performance and/or reliability for both calls. Please consider changing the CacheLookupPolicy to take advantage of request queuing and token cache.", silentRequest.correlationId);
1273
+ return invokeAsync(this.acquireTokenBySilentIframe.bind(this), PerformanceEvents.AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest);
1274
+ }
1275
+ }
1276
+ else {
1277
+ // Error cannot be silently resolved or iframe renewal is not allowed, interaction required
1278
+ throw refreshTokenError;
1279
+ }
1280
+ });
1281
+ return result
1282
+ .then((response) => {
1283
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, InteractionType.Silent, response);
1284
+ if (request.correlationId) {
1285
+ this.performanceClient.addFields({
1286
+ fromCache: response.fromCache,
1287
+ isNativeBroker: response.fromNativeBroker,
1288
+ requestId: response.requestId,
1289
+ }, request.correlationId);
1290
+ }
1291
+ return response;
1292
+ })
1293
+ .catch((tokenRenewalError) => {
1294
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, InteractionType.Silent, null, tokenRenewalError);
1295
+ throw tokenRenewalError;
1296
+ })
1297
+ .finally(() => {
1298
+ document.removeEventListener("visibilitychange", trackPageVisibility);
1299
+ });
1300
+ }
1301
+ /**
1302
+ * AcquireTokenSilent without the iframe fallback. This is used to enable the correct fallbacks in cases where there's a potential for multiple silent requests to be made in parallel and prevent those requests from making concurrent iframe requests.
1303
+ * @param silentRequest
1304
+ * @param cacheLookupPolicy
1305
+ * @returns
1306
+ */
1307
+ async acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy) {
1308
+ if (NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeExtensionProvider, silentRequest.authenticationScheme) &&
1309
+ silentRequest.account.nativeAccountId) {
1310
+ this.logger.verbose("acquireTokenSilent - attempting to acquire token from native platform");
1311
+ return this.acquireTokenNative(silentRequest, ApiId.acquireTokenSilent_silentFlow).catch(async (e) => {
1312
+ // If native token acquisition fails for availability reasons fallback to web flow
1313
+ if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
1314
+ this.logger.verbose("acquireTokenSilent - native platform unavailable, falling back to web flow");
1315
+ this.nativeExtensionProvider = undefined; // Prevent future requests from continuing to attempt
1316
+ // Cache will not contain tokens, given that previous WAM requests succeeded. Skip cache and RT renewal and go straight to iframe renewal
1317
+ throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
1318
+ }
1319
+ throw e;
1320
+ });
1321
+ }
1322
+ else {
1323
+ this.logger.verbose("acquireTokenSilent - attempting to acquire token from web flow");
1324
+ return invokeAsync(this.acquireTokenFromCache.bind(this), PerformanceEvents.AcquireTokenFromCache, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy).catch((cacheError) => {
1325
+ if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
1326
+ throw cacheError;
1327
+ }
1328
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_NETWORK_START, InteractionType.Silent, silentRequest);
1329
+ return invokeAsync(this.acquireTokenByRefreshToken.bind(this), PerformanceEvents.AcquireTokenByRefreshToken, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy);
1330
+ });
1331
+ }
1332
+ }
1333
+ }
1334
+ /**
1335
+ * Determines whether an error thrown by the refresh token endpoint can be resolved without interaction
1336
+ * @param refreshTokenError
1337
+ * @param silentRequest
1338
+ * @param cacheLookupPolicy
1339
+ * @returns
1340
+ */
1341
+ function checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy) {
1342
+ const noInteractionRequired = !(refreshTokenError instanceof InteractionRequiredAuthError &&
1343
+ // For refresh token errors, bad_token does not always require interaction (silently resolvable)
1344
+ refreshTokenError.subError !==
1345
+ InteractionRequiredAuthErrorCodes.badToken);
1346
+ // Errors that result when the refresh token needs to be replaced
1347
+ const refreshTokenRefreshRequired = refreshTokenError.errorCode === BrowserConstants.INVALID_GRANT_ERROR ||
1348
+ refreshTokenError.errorCode ===
1349
+ ClientAuthErrorCodes.tokenRefreshRequired;
1350
+ // Errors that may be resolved before falling back to interaction (through iframe renewal)
1351
+ const isSilentlyResolvable = (noInteractionRequired && refreshTokenRefreshRequired) ||
1352
+ refreshTokenError.errorCode ===
1353
+ InteractionRequiredAuthErrorCodes.noTokensFound ||
1354
+ refreshTokenError.errorCode ===
1355
+ InteractionRequiredAuthErrorCodes.refreshTokenExpired;
1356
+ // Only these policies allow for an iframe renewal attempt
1357
+ const tryIframeRenewal = iFrameRenewalPolicies.includes(cacheLookupPolicy);
1358
+ return isSilentlyResolvable && tryIframeRenewal;
1341
1359
  }
1342
1360
 
1343
1361
  export { StandardController };