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