@azure/msal-browser 3.0.2 → 3.2.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 (280) hide show
  1. package/dist/app/IPublicClientApplication.d.ts +2 -0
  2. package/dist/app/IPublicClientApplication.d.ts.map +1 -1
  3. package/dist/app/IPublicClientApplication.mjs +22 -18
  4. package/dist/app/IPublicClientApplication.mjs.map +1 -1
  5. package/dist/app/PublicClientApplication.d.ts +20 -6
  6. package/dist/app/PublicClientApplication.d.ts.map +1 -1
  7. package/dist/app/PublicClientApplication.mjs +24 -7
  8. package/dist/app/PublicClientApplication.mjs.map +1 -1
  9. package/dist/broker/nativeBroker/NativeMessageHandler.d.ts +3 -4
  10. package/dist/broker/nativeBroker/NativeMessageHandler.d.ts.map +1 -1
  11. package/dist/broker/nativeBroker/NativeMessageHandler.mjs +17 -16
  12. package/dist/broker/nativeBroker/NativeMessageHandler.mjs.map +1 -1
  13. package/dist/broker/nativeBroker/NativeStatusCodes.d.ts +8 -0
  14. package/dist/broker/nativeBroker/NativeStatusCodes.d.ts.map +1 -0
  15. package/dist/broker/nativeBroker/NativeStatusCodes.mjs +16 -0
  16. package/dist/broker/nativeBroker/NativeStatusCodes.mjs.map +1 -0
  17. package/dist/cache/AsyncMemoryStorage.mjs +4 -3
  18. package/dist/cache/AsyncMemoryStorage.mjs.map +1 -1
  19. package/dist/cache/BrowserCacheManager.d.ts +10 -3
  20. package/dist/cache/BrowserCacheManager.d.ts.map +1 -1
  21. package/dist/cache/BrowserCacheManager.mjs +58 -29
  22. package/dist/cache/BrowserCacheManager.mjs.map +1 -1
  23. package/dist/cache/BrowserStorage.d.ts.map +1 -1
  24. package/dist/cache/BrowserStorage.mjs +7 -9
  25. package/dist/cache/BrowserStorage.mjs.map +1 -1
  26. package/dist/cache/CryptoKeyStore.mjs +1 -1
  27. package/dist/cache/CryptoKeyStore.mjs.map +1 -1
  28. package/dist/cache/DatabaseStorage.d.ts.map +1 -1
  29. package/dist/cache/DatabaseStorage.mjs +9 -8
  30. package/dist/cache/DatabaseStorage.mjs.map +1 -1
  31. package/dist/cache/MemoryStorage.mjs +1 -1
  32. package/dist/cache/MemoryStorage.mjs.map +1 -1
  33. package/dist/cache/TokenCache.d.ts.map +1 -1
  34. package/dist/cache/TokenCache.mjs +30 -30
  35. package/dist/cache/TokenCache.mjs.map +1 -1
  36. package/dist/config/Configuration.d.ts +1 -0
  37. package/dist/config/Configuration.d.ts.map +1 -1
  38. package/dist/config/Configuration.mjs +12 -16
  39. package/dist/config/Configuration.mjs.map +1 -1
  40. package/dist/controllers/ControllerFactory.mjs +1 -1
  41. package/dist/controllers/ControllerFactory.mjs.map +1 -1
  42. package/dist/controllers/IController.d.ts +5 -28
  43. package/dist/controllers/IController.d.ts.map +1 -1
  44. package/dist/controllers/StandardController.d.ts +17 -31
  45. package/dist/controllers/StandardController.d.ts.map +1 -1
  46. package/dist/controllers/StandardController.mjs +78 -83
  47. package/dist/controllers/StandardController.mjs.map +1 -1
  48. package/dist/crypto/BrowserCrypto.d.ts +44 -49
  49. package/dist/crypto/BrowserCrypto.d.ts.map +1 -1
  50. package/dist/crypto/BrowserCrypto.mjs +78 -77
  51. package/dist/crypto/BrowserCrypto.mjs.map +1 -1
  52. package/dist/crypto/CryptoOps.d.ts +1 -10
  53. package/dist/crypto/CryptoOps.d.ts.map +1 -1
  54. package/dist/crypto/CryptoOps.mjs +23 -34
  55. package/dist/crypto/CryptoOps.mjs.map +1 -1
  56. package/dist/crypto/PkceGenerator.d.ts +6 -22
  57. package/dist/crypto/PkceGenerator.d.ts.map +1 -1
  58. package/dist/crypto/PkceGenerator.mjs +48 -49
  59. package/dist/crypto/PkceGenerator.mjs.map +1 -1
  60. package/dist/crypto/SignedHttpRequest.mjs +1 -1
  61. package/dist/crypto/SignedHttpRequest.mjs.map +1 -1
  62. package/dist/encode/Base64Decode.d.ts +6 -19
  63. package/dist/encode/Base64Decode.d.ts.map +1 -1
  64. package/dist/encode/Base64Decode.mjs +31 -68
  65. package/dist/encode/Base64Decode.mjs.map +1 -1
  66. package/dist/encode/Base64Encode.d.ts +15 -27
  67. package/dist/encode/Base64Encode.d.ts.map +1 -1
  68. package/dist/encode/Base64Encode.mjs +36 -75
  69. package/dist/encode/Base64Encode.mjs.map +1 -1
  70. package/dist/error/BrowserAuthError.d.ts +63 -195
  71. package/dist/error/BrowserAuthError.d.ts.map +1 -1
  72. package/dist/error/BrowserAuthError.mjs +159 -381
  73. package/dist/error/BrowserAuthError.mjs.map +1 -1
  74. package/dist/error/BrowserAuthErrorCodes.d.ts +46 -0
  75. package/dist/error/BrowserAuthErrorCodes.d.ts.map +1 -0
  76. package/dist/error/BrowserAuthErrorCodes.mjs +54 -0
  77. package/dist/error/BrowserAuthErrorCodes.mjs.map +1 -0
  78. package/dist/error/BrowserConfigurationAuthError.d.ts +9 -46
  79. package/dist/error/BrowserConfigurationAuthError.d.ts.map +1 -1
  80. package/dist/error/BrowserConfigurationAuthError.mjs +20 -73
  81. package/dist/error/BrowserConfigurationAuthError.mjs.map +1 -1
  82. package/dist/error/BrowserConfigurationAuthErrorCodes.d.ts +4 -0
  83. package/dist/error/BrowserConfigurationAuthErrorCodes.d.ts.map +1 -0
  84. package/dist/error/BrowserConfigurationAuthErrorCodes.mjs +12 -0
  85. package/dist/error/BrowserConfigurationAuthErrorCodes.mjs.map +1 -0
  86. package/dist/error/NativeAuthError.d.ts +17 -45
  87. package/dist/error/NativeAuthError.d.ts.map +1 -1
  88. package/dist/error/NativeAuthError.mjs +49 -79
  89. package/dist/error/NativeAuthError.mjs.map +1 -1
  90. package/dist/error/NativeAuthErrorCodes.d.ts +3 -0
  91. package/dist/error/NativeAuthErrorCodes.d.ts.map +1 -0
  92. package/dist/error/NativeAuthErrorCodes.mjs +11 -0
  93. package/dist/error/NativeAuthErrorCodes.mjs.map +1 -0
  94. package/dist/event/EventHandler.d.ts.map +1 -1
  95. package/dist/event/EventHandler.mjs +3 -2
  96. package/dist/event/EventHandler.mjs.map +1 -1
  97. package/dist/event/EventMessage.mjs +1 -1
  98. package/dist/event/EventMessage.mjs.map +1 -1
  99. package/dist/event/EventType.mjs +1 -1
  100. package/dist/event/EventType.mjs.map +1 -1
  101. package/dist/index.d.ts +6 -6
  102. package/dist/index.d.ts.map +1 -1
  103. package/dist/index.mjs +8 -4
  104. package/dist/index.mjs.map +1 -1
  105. package/dist/interaction_client/BaseInteractionClient.d.ts +2 -1
  106. package/dist/interaction_client/BaseInteractionClient.d.ts.map +1 -1
  107. package/dist/interaction_client/BaseInteractionClient.mjs +7 -8
  108. package/dist/interaction_client/BaseInteractionClient.mjs.map +1 -1
  109. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.mjs +1 -1
  110. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.mjs.map +1 -1
  111. package/dist/interaction_client/NativeInteractionClient.d.ts +4 -10
  112. package/dist/interaction_client/NativeInteractionClient.d.ts.map +1 -1
  113. package/dist/interaction_client/NativeInteractionClient.mjs +32 -38
  114. package/dist/interaction_client/NativeInteractionClient.mjs.map +1 -1
  115. package/dist/interaction_client/PopupClient.d.ts.map +1 -1
  116. package/dist/interaction_client/PopupClient.mjs +16 -15
  117. package/dist/interaction_client/PopupClient.mjs.map +1 -1
  118. package/dist/interaction_client/RedirectClient.d.ts.map +1 -1
  119. package/dist/interaction_client/RedirectClient.mjs +7 -6
  120. package/dist/interaction_client/RedirectClient.mjs.map +1 -1
  121. package/dist/interaction_client/SilentAuthCodeClient.d.ts.map +1 -1
  122. package/dist/interaction_client/SilentAuthCodeClient.mjs +9 -11
  123. package/dist/interaction_client/SilentAuthCodeClient.mjs.map +1 -1
  124. package/dist/interaction_client/SilentCacheClient.d.ts +4 -2
  125. package/dist/interaction_client/SilentCacheClient.d.ts.map +1 -1
  126. package/dist/interaction_client/SilentCacheClient.mjs +19 -25
  127. package/dist/interaction_client/SilentCacheClient.mjs.map +1 -1
  128. package/dist/interaction_client/SilentIframeClient.d.ts.map +1 -1
  129. package/dist/interaction_client/SilentIframeClient.mjs +20 -47
  130. package/dist/interaction_client/SilentIframeClient.mjs.map +1 -1
  131. package/dist/interaction_client/SilentRefreshClient.d.ts.map +1 -1
  132. package/dist/interaction_client/SilentRefreshClient.mjs +11 -20
  133. package/dist/interaction_client/SilentRefreshClient.mjs.map +1 -1
  134. package/dist/interaction_client/StandardInteractionClient.d.ts.map +1 -1
  135. package/dist/interaction_client/StandardInteractionClient.mjs +18 -38
  136. package/dist/interaction_client/StandardInteractionClient.mjs.map +1 -1
  137. package/dist/interaction_handler/InteractionHandler.d.ts.map +1 -1
  138. package/dist/interaction_handler/InteractionHandler.mjs +13 -16
  139. package/dist/interaction_handler/InteractionHandler.mjs.map +1 -1
  140. package/dist/interaction_handler/RedirectHandler.d.ts.map +1 -1
  141. package/dist/interaction_handler/RedirectHandler.mjs +12 -11
  142. package/dist/interaction_handler/RedirectHandler.mjs.map +1 -1
  143. package/dist/interaction_handler/SilentHandler.d.ts.map +1 -1
  144. package/dist/interaction_handler/SilentHandler.mjs +11 -11
  145. package/dist/interaction_handler/SilentHandler.mjs.map +1 -1
  146. package/dist/navigation/NavigationClient.mjs +1 -1
  147. package/dist/navigation/NavigationClient.mjs.map +1 -1
  148. package/dist/network/FetchClient.d.ts.map +1 -1
  149. package/dist/network/FetchClient.mjs +9 -8
  150. package/dist/network/FetchClient.mjs.map +1 -1
  151. package/dist/operatingcontext/BaseOperatingContext.mjs +1 -1
  152. package/dist/operatingcontext/BaseOperatingContext.mjs.map +1 -1
  153. package/dist/operatingcontext/StandardOperatingContext.mjs +1 -1
  154. package/dist/operatingcontext/StandardOperatingContext.mjs.map +1 -1
  155. package/dist/operatingcontext/TeamsAppOperatingContext.mjs +1 -1
  156. package/dist/operatingcontext/TeamsAppOperatingContext.mjs.map +1 -1
  157. package/dist/packageMetadata.d.ts +1 -1
  158. package/dist/packageMetadata.mjs +2 -2
  159. package/dist/packageMetadata.mjs.map +1 -1
  160. package/dist/request/ClearCacheRequest.d.ts +11 -0
  161. package/dist/request/ClearCacheRequest.d.ts.map +1 -0
  162. package/dist/telemetry/BrowserPerformanceClient.d.ts +2 -4
  163. package/dist/telemetry/BrowserPerformanceClient.d.ts.map +1 -1
  164. package/dist/telemetry/BrowserPerformanceClient.mjs +2 -6
  165. package/dist/telemetry/BrowserPerformanceClient.mjs.map +1 -1
  166. package/dist/telemetry/BrowserPerformanceMeasurement.mjs +1 -1
  167. package/dist/telemetry/BrowserPerformanceMeasurement.mjs.map +1 -1
  168. package/dist/utils/BrowserConstants.mjs +1 -1
  169. package/dist/utils/BrowserConstants.mjs.map +1 -1
  170. package/dist/utils/BrowserProtocolUtils.d.ts.map +1 -1
  171. package/dist/utils/BrowserProtocolUtils.mjs +4 -4
  172. package/dist/utils/BrowserProtocolUtils.mjs.map +1 -1
  173. package/dist/utils/BrowserStringUtils.mjs +1 -1
  174. package/dist/utils/BrowserStringUtils.mjs.map +1 -1
  175. package/dist/utils/BrowserUtils.d.ts +0 -9
  176. package/dist/utils/BrowserUtils.d.ts.map +1 -1
  177. package/dist/utils/BrowserUtils.mjs +8 -33
  178. package/dist/utils/BrowserUtils.mjs.map +1 -1
  179. package/lib/msal-browser.cjs +8729 -9566
  180. package/lib/msal-browser.cjs.map +1 -1
  181. package/lib/msal-browser.js +8729 -9566
  182. package/lib/msal-browser.js.map +1 -1
  183. package/lib/msal-browser.min.js +68 -62
  184. package/package.json +7 -5
  185. package/src/app/IPublicClientApplication.ts +236 -0
  186. package/src/app/PublicClientApplication.ts +417 -0
  187. package/src/broker/nativeBroker/NativeMessageHandler.ts +416 -0
  188. package/src/broker/nativeBroker/NativeRequest.ts +52 -0
  189. package/src/broker/nativeBroker/NativeResponse.ts +56 -0
  190. package/src/broker/nativeBroker/NativeStatusCodes.ts +13 -0
  191. package/src/cache/AsyncMemoryStorage.ts +158 -0
  192. package/src/cache/BrowserCacheManager.ts +2009 -0
  193. package/src/cache/BrowserStorage.ts +52 -0
  194. package/src/cache/CryptoKeyStore.ts +63 -0
  195. package/src/cache/DatabaseStorage.ts +287 -0
  196. package/src/cache/IAsyncMemoryStorage.ts +36 -0
  197. package/src/cache/ITokenCache.ts +21 -0
  198. package/src/cache/IWindowStorage.ts +36 -0
  199. package/src/cache/MemoryStorage.ts +42 -0
  200. package/src/cache/TokenCache.ts +484 -0
  201. package/src/config/Configuration.ts +383 -0
  202. package/src/controllers/ControllerFactory.ts +55 -0
  203. package/src/controllers/IController.ts +134 -0
  204. package/src/controllers/StandardController.ts +2170 -0
  205. package/src/crypto/BrowserCrypto.ts +151 -0
  206. package/src/crypto/CryptoOps.ts +235 -0
  207. package/src/crypto/PkceGenerator.ts +115 -0
  208. package/src/crypto/SignedHttpRequest.ts +76 -0
  209. package/src/encode/Base64Decode.ts +46 -0
  210. package/src/encode/Base64Encode.ts +52 -0
  211. package/src/error/BrowserAuthError.ts +352 -0
  212. package/src/error/BrowserAuthErrorCodes.ts +57 -0
  213. package/src/error/BrowserConfigurationAuthError.ts +64 -0
  214. package/src/error/BrowserConfigurationAuthErrorCodes.ts +9 -0
  215. package/src/error/NativeAuthError.ts +113 -0
  216. package/src/error/NativeAuthErrorCodes.ts +7 -0
  217. package/src/event/EventHandler.ts +177 -0
  218. package/src/event/EventMessage.ts +125 -0
  219. package/src/event/EventType.ts +33 -0
  220. package/src/index.ts +157 -0
  221. package/src/interaction_client/BaseInteractionClient.ts +307 -0
  222. package/src/interaction_client/HybridSpaAuthorizationCodeClient.ts +16 -0
  223. package/src/interaction_client/NativeInteractionClient.ts +925 -0
  224. package/src/interaction_client/PopupClient.ts +926 -0
  225. package/src/interaction_client/RedirectClient.ts +616 -0
  226. package/src/interaction_client/SilentAuthCodeClient.ts +165 -0
  227. package/src/interaction_client/SilentCacheClient.ts +125 -0
  228. package/src/interaction_client/SilentIframeClient.ts +301 -0
  229. package/src/interaction_client/SilentRefreshClient.ts +118 -0
  230. package/src/interaction_client/StandardInteractionClient.ts +450 -0
  231. package/src/interaction_handler/InteractionHandler.ts +251 -0
  232. package/src/interaction_handler/RedirectHandler.ts +229 -0
  233. package/src/interaction_handler/SilentHandler.ts +269 -0
  234. package/src/navigation/INavigationClient.ts +23 -0
  235. package/src/navigation/NavigationClient.ts +55 -0
  236. package/src/navigation/NavigationOptions.ts +18 -0
  237. package/src/network/FetchClient.ts +130 -0
  238. package/src/operatingcontext/BaseOperatingContext.ts +82 -0
  239. package/src/operatingcontext/StandardOperatingContext.ts +49 -0
  240. package/src/operatingcontext/TeamsAppOperatingContext.ts +48 -0
  241. package/src/packageMetadata.ts +3 -0
  242. package/src/request/AuthorizationCodeRequest.ts +19 -0
  243. package/src/request/AuthorizationUrlRequest.ts +17 -0
  244. package/src/request/ClearCacheRequest.ts +16 -0
  245. package/src/request/EndSessionPopupRequest.ts +26 -0
  246. package/src/request/EndSessionRequest.ts +23 -0
  247. package/src/request/PopupRequest.ts +51 -0
  248. package/src/request/PopupWindowAttributes.ts +22 -0
  249. package/src/request/RedirectRequest.ts +51 -0
  250. package/src/request/SilentRequest.ts +49 -0
  251. package/src/request/SsoSilentRequest.ts +44 -0
  252. package/src/response/AuthenticationResult.ts +13 -0
  253. package/src/telemetry/BrowserPerformanceClient.ts +226 -0
  254. package/src/telemetry/BrowserPerformanceMeasurement.ts +144 -0
  255. package/src/utils/BrowserConstants.ts +241 -0
  256. package/src/utils/BrowserProtocolUtils.ts +58 -0
  257. package/src/utils/BrowserStringUtils.ts +143 -0
  258. package/src/utils/BrowserUtils.ts +156 -0
  259. package/dist/crypto/GuidGenerator.d.ts +0 -13
  260. package/dist/crypto/GuidGenerator.d.ts.map +0 -1
  261. package/dist/crypto/GuidGenerator.mjs +0 -104
  262. package/dist/crypto/GuidGenerator.mjs.map +0 -1
  263. package/dist/crypto/ISubtleCrypto.d.ts +0 -10
  264. package/dist/crypto/ISubtleCrypto.d.ts.map +0 -1
  265. package/dist/crypto/ModernBrowserCrypto.d.ts +0 -10
  266. package/dist/crypto/ModernBrowserCrypto.d.ts.map +0 -1
  267. package/dist/crypto/ModernBrowserCrypto.mjs +0 -31
  268. package/dist/crypto/ModernBrowserCrypto.mjs.map +0 -1
  269. package/dist/internals.d.ts +0 -23
  270. package/dist/internals.d.ts.map +0 -1
  271. package/dist/internals.mjs +0 -28
  272. package/dist/internals.mjs.map +0 -1
  273. package/dist/network/XhrClient.d.ts +0 -41
  274. package/dist/network/XhrClient.d.ts.map +0 -1
  275. package/dist/network/XhrClient.mjs +0 -125
  276. package/dist/network/XhrClient.mjs.map +0 -1
  277. package/dist/utils/MathUtils.d.ts +0 -12
  278. package/dist/utils/MathUtils.d.ts.map +0 -1
  279. package/dist/utils/MathUtils.mjs +0 -26
  280. package/dist/utils/MathUtils.mjs.map +0 -1
@@ -0,0 +1,2170 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { CryptoOps } from "../crypto/CryptoOps";
7
+ import {
8
+ InteractionRequiredAuthError,
9
+ AccountInfo,
10
+ Constants,
11
+ INetworkModule,
12
+ Logger,
13
+ CommonSilentFlowRequest,
14
+ ICrypto,
15
+ DEFAULT_CRYPTO_IMPLEMENTATION,
16
+ AuthError,
17
+ PerformanceEvents,
18
+ PerformanceCallbackFunction,
19
+ IPerformanceClient,
20
+ BaseAuthRequest,
21
+ PromptValue,
22
+ InProgressPerformanceEvent,
23
+ RequestThumbprint,
24
+ ServerError,
25
+ AccountEntity,
26
+ ServerResponseType,
27
+ UrlString,
28
+ invokeAsync,
29
+ createClientAuthError,
30
+ ClientAuthErrorCodes,
31
+ AccountFilter,
32
+ } from "@azure/msal-common";
33
+ import {
34
+ BrowserCacheManager,
35
+ DEFAULT_BROWSER_CACHE_MANAGER,
36
+ } from "../cache/BrowserCacheManager";
37
+ import { BrowserConfiguration, CacheOptions } from "../config/Configuration";
38
+ import {
39
+ InteractionType,
40
+ ApiId,
41
+ BrowserCacheLocation,
42
+ WrapperSKU,
43
+ TemporaryCacheKeys,
44
+ CacheLookupPolicy,
45
+ DEFAULT_REQUEST,
46
+ BrowserConstants,
47
+ } from "../utils/BrowserConstants";
48
+ import { BrowserUtils } from "../utils/BrowserUtils";
49
+ import { RedirectRequest } from "../request/RedirectRequest";
50
+ import { PopupRequest } from "../request/PopupRequest";
51
+ import { SsoSilentRequest } from "../request/SsoSilentRequest";
52
+ import { EventCallbackFunction, EventError } from "../event/EventMessage";
53
+ import { EventType } from "../event/EventType";
54
+ import { EndSessionRequest } from "../request/EndSessionRequest";
55
+ import {
56
+ BrowserConfigurationAuthErrorCodes,
57
+ createBrowserConfigurationAuthError,
58
+ } from "../error/BrowserConfigurationAuthError";
59
+ import { EndSessionPopupRequest } from "../request/EndSessionPopupRequest";
60
+ import { INavigationClient } from "../navigation/INavigationClient";
61
+ import { EventHandler } from "../event/EventHandler";
62
+ import { PopupClient } from "../interaction_client/PopupClient";
63
+ import { RedirectClient } from "../interaction_client/RedirectClient";
64
+ import { SilentIframeClient } from "../interaction_client/SilentIframeClient";
65
+ import { SilentRefreshClient } from "../interaction_client/SilentRefreshClient";
66
+ import { TokenCache } from "../cache/TokenCache";
67
+ import { ITokenCache } from "../cache/ITokenCache";
68
+ import { NativeInteractionClient } from "../interaction_client/NativeInteractionClient";
69
+ import { NativeMessageHandler } from "../broker/nativeBroker/NativeMessageHandler";
70
+ import { SilentRequest } from "../request/SilentRequest";
71
+ import {
72
+ NativeAuthError,
73
+ isFatalNativeAuthError,
74
+ } from "../error/NativeAuthError";
75
+ import { SilentCacheClient } from "../interaction_client/SilentCacheClient";
76
+ import { SilentAuthCodeClient } from "../interaction_client/SilentAuthCodeClient";
77
+ import {
78
+ createBrowserAuthError,
79
+ BrowserAuthErrorCodes,
80
+ } from "../error/BrowserAuthError";
81
+ import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest";
82
+ import { NativeTokenRequest } from "../broker/nativeBroker/NativeRequest";
83
+ import { StandardOperatingContext } from "../operatingcontext/StandardOperatingContext";
84
+ import { BaseOperatingContext } from "../operatingcontext/BaseOperatingContext";
85
+ import { IController } from "./IController";
86
+ import { AuthenticationResult } from "../response/AuthenticationResult";
87
+ import { ClearCacheRequest } from "../request/ClearCacheRequest";
88
+ import { createNewGuid } from "../crypto/BrowserCrypto";
89
+
90
+ export class StandardController implements IController {
91
+ // OperatingContext
92
+ protected readonly operatingContext: StandardOperatingContext;
93
+
94
+ // Crypto interface implementation
95
+ protected readonly browserCrypto: ICrypto;
96
+
97
+ // Storage interface implementation
98
+ protected readonly browserStorage: BrowserCacheManager;
99
+
100
+ // Native Cache in memory storage implementation
101
+ protected readonly nativeInternalStorage: BrowserCacheManager;
102
+
103
+ // Network interface implementation
104
+ protected readonly networkClient: INetworkModule;
105
+
106
+ // Navigation interface implementation
107
+ protected navigationClient: INavigationClient;
108
+
109
+ // Input configuration by developer/user
110
+ protected readonly config: BrowserConfiguration;
111
+
112
+ // Token cache implementation
113
+ private tokenCache: TokenCache;
114
+
115
+ // Logger
116
+ protected logger: Logger;
117
+
118
+ // Flag to indicate if in browser environment
119
+ protected isBrowserEnvironment: boolean;
120
+
121
+ protected readonly eventHandler: EventHandler;
122
+
123
+ // Redirect Response Object
124
+ protected readonly redirectResponse: Map<
125
+ string,
126
+ Promise<AuthenticationResult | null>
127
+ >;
128
+
129
+ // Native Extension Provider
130
+ protected nativeExtensionProvider: NativeMessageHandler | undefined;
131
+
132
+ // Hybrid auth code responses
133
+ private hybridAuthCodeResponses: Map<string, Promise<AuthenticationResult>>;
134
+
135
+ // Performance telemetry client
136
+ protected readonly performanceClient: IPerformanceClient;
137
+
138
+ // Flag representing whether or not the initialize API has been called and completed
139
+ protected initialized: boolean;
140
+
141
+ // Active requests
142
+ private activeSilentTokenRequests: Map<
143
+ string,
144
+ Promise<AuthenticationResult>
145
+ >;
146
+ private atsAsyncMeasurement?: InProgressPerformanceEvent = undefined;
147
+
148
+ private ssoSilentMeasurement?: InProgressPerformanceEvent;
149
+ private acquireTokenByCodeAsyncMeasurement?: InProgressPerformanceEvent;
150
+ /**
151
+ * @constructor
152
+ * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
153
+ *
154
+ * Important attributes in the Configuration object for auth are:
155
+ * - 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
156
+ * - authority: the authority URL for your application.
157
+ * - redirect_uri: the uri of your application registered in the portal.
158
+ *
159
+ * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
160
+ * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
161
+ * 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).
162
+ * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
163
+ * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
164
+ * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
165
+ *
166
+ * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
167
+ * Full B2C functionality will be available in this library in future versions.
168
+ *
169
+ * @param configuration Object for the MSAL PublicClientApplication instance
170
+ */
171
+ constructor(operatingContext: StandardOperatingContext) {
172
+ this.operatingContext = operatingContext;
173
+ this.isBrowserEnvironment =
174
+ this.operatingContext.isBrowserEnvironment();
175
+ // Set the configuration.
176
+ this.config = operatingContext.getConfig();
177
+ this.initialized = false;
178
+
179
+ // Initialize logger
180
+ this.logger = this.operatingContext.getLogger();
181
+
182
+ // Initialize the network module class.
183
+ this.networkClient = this.config.system.networkClient;
184
+
185
+ // Initialize the navigation client class.
186
+ this.navigationClient = this.config.system.navigationClient;
187
+
188
+ // Initialize redirectResponse Map
189
+ this.redirectResponse = new Map();
190
+
191
+ // Initial hybrid spa map
192
+ this.hybridAuthCodeResponses = new Map();
193
+
194
+ // Initialize performance client
195
+ this.performanceClient = this.config.telemetry.client;
196
+
197
+ // Initialize the crypto class.
198
+ this.browserCrypto = this.isBrowserEnvironment
199
+ ? new CryptoOps(this.logger, this.performanceClient)
200
+ : DEFAULT_CRYPTO_IMPLEMENTATION;
201
+
202
+ this.eventHandler = new EventHandler(this.logger, this.browserCrypto);
203
+
204
+ // Initialize the browser storage class.
205
+ this.browserStorage = this.isBrowserEnvironment
206
+ ? new BrowserCacheManager(
207
+ this.config.auth.clientId,
208
+ this.config.cache,
209
+ this.browserCrypto,
210
+ this.logger
211
+ )
212
+ : DEFAULT_BROWSER_CACHE_MANAGER(
213
+ this.config.auth.clientId,
214
+ this.logger
215
+ );
216
+
217
+ // initialize in memory storage for native flows
218
+ const nativeCacheOptions: Required<CacheOptions> = {
219
+ cacheLocation: BrowserCacheLocation.MemoryStorage,
220
+ temporaryCacheLocation: BrowserCacheLocation.MemoryStorage,
221
+ storeAuthStateInCookie: false,
222
+ secureCookies: false,
223
+ cacheMigrationEnabled: false,
224
+ claimsBasedCachingEnabled: false,
225
+ };
226
+ this.nativeInternalStorage = new BrowserCacheManager(
227
+ this.config.auth.clientId,
228
+ nativeCacheOptions,
229
+ this.browserCrypto,
230
+ this.logger
231
+ );
232
+
233
+ // Initialize the token cache
234
+ this.tokenCache = new TokenCache(
235
+ this.config,
236
+ this.browserStorage,
237
+ this.logger,
238
+ this.browserCrypto
239
+ );
240
+
241
+ this.activeSilentTokenRequests = new Map();
242
+
243
+ // Register listener functions
244
+ this.trackPageVisibility = this.trackPageVisibility.bind(this);
245
+
246
+ // Register listener functions
247
+ this.trackPageVisibilityWithMeasurement =
248
+ this.trackPageVisibilityWithMeasurement.bind(this);
249
+ }
250
+
251
+ static async createController(
252
+ operatingContext: BaseOperatingContext
253
+ ): Promise<IController> {
254
+ const controller = new StandardController(operatingContext);
255
+ await controller.initialize();
256
+ return controller;
257
+ }
258
+
259
+ private trackPageVisibility(): void {
260
+ if (!this.atsAsyncMeasurement) {
261
+ return;
262
+ }
263
+ this.logger.info("Perf: Visibility change detected");
264
+ this.atsAsyncMeasurement.increment({
265
+ visibilityChangeCount: 1,
266
+ });
267
+ }
268
+
269
+ /**
270
+ * Initializer function to perform async startup tasks such as connecting to WAM extension
271
+ */
272
+ async initialize(): Promise<void> {
273
+ this.logger.trace("initialize called");
274
+ if (this.initialized) {
275
+ this.logger.info(
276
+ "initialize has already been called, exiting early."
277
+ );
278
+ return;
279
+ }
280
+
281
+ const allowNativeBroker = this.config.system.allowNativeBroker;
282
+ const initMeasurement = this.performanceClient.startMeasurement(
283
+ PerformanceEvents.InitializeClientApplication
284
+ );
285
+ this.eventHandler.emitEvent(EventType.INITIALIZE_START);
286
+
287
+ if (allowNativeBroker) {
288
+ try {
289
+ this.nativeExtensionProvider =
290
+ await NativeMessageHandler.createProvider(
291
+ this.logger,
292
+ this.config.system.nativeBrokerHandshakeTimeout,
293
+ this.performanceClient
294
+ );
295
+ } catch (e) {
296
+ this.logger.verbose(e as string);
297
+ }
298
+ }
299
+
300
+ if (!this.config.cache.claimsBasedCachingEnabled) {
301
+ this.logger.verbose(
302
+ "Claims-based caching is disabled. Clearing the previous cache with claims"
303
+ );
304
+
305
+ await invokeAsync(
306
+ this.browserStorage.clearTokensAndKeysWithClaims.bind(
307
+ this.browserStorage
308
+ ),
309
+ PerformanceEvents.ClearTokensAndKeysWithClaims,
310
+ this.logger,
311
+ this.performanceClient
312
+ )(this.performanceClient);
313
+ }
314
+
315
+ this.initialized = true;
316
+ this.eventHandler.emitEvent(EventType.INITIALIZE_END);
317
+
318
+ initMeasurement.end({ allowNativeBroker, success: true });
319
+ }
320
+
321
+ // #region Redirect Flow
322
+
323
+ /**
324
+ * Event handler function which allows users to fire events after the PublicClientApplication object
325
+ * has loaded during redirect flows. This should be invoked on all page loads involved in redirect
326
+ * auth flows.
327
+ * @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.
328
+ * @returns Token response or null. If the return value is null, then no auth redirect was detected.
329
+ */
330
+ async handleRedirectPromise(
331
+ hash?: string
332
+ ): Promise<AuthenticationResult | null> {
333
+ this.logger.verbose("handleRedirectPromise called");
334
+ // Block token acquisition before initialize has been called
335
+ BrowserUtils.blockAPICallsBeforeInitialize(this.initialized);
336
+
337
+ let foundServerResponse = hash;
338
+
339
+ if (
340
+ this.config.auth.OIDCOptions?.serverResponseType ===
341
+ ServerResponseType.QUERY
342
+ ) {
343
+ const url = window.location.href;
344
+ foundServerResponse = UrlString.parseQueryServerResponse(url);
345
+ }
346
+
347
+ const loggedInAccounts = this.getAllAccounts();
348
+ if (this.isBrowserEnvironment) {
349
+ /**
350
+ * Store the promise on the PublicClientApplication instance if this is the first invocation of handleRedirectPromise,
351
+ * otherwise return the promise from the first invocation. Prevents race conditions when handleRedirectPromise is called
352
+ * several times concurrently.
353
+ */
354
+ const redirectResponseKey =
355
+ foundServerResponse || Constants.EMPTY_STRING;
356
+ let response = this.redirectResponse.get(redirectResponseKey);
357
+ if (typeof response === "undefined") {
358
+ this.eventHandler.emitEvent(
359
+ EventType.HANDLE_REDIRECT_START,
360
+ InteractionType.Redirect
361
+ );
362
+ this.logger.verbose(
363
+ "handleRedirectPromise has been called for the first time, storing the promise"
364
+ );
365
+
366
+ const request: NativeTokenRequest | null =
367
+ this.browserStorage.getCachedNativeRequest();
368
+ let redirectResponse: Promise<AuthenticationResult | null>;
369
+ if (
370
+ request &&
371
+ NativeMessageHandler.isNativeAvailable(
372
+ this.config,
373
+ this.logger,
374
+ this.nativeExtensionProvider
375
+ ) &&
376
+ this.nativeExtensionProvider &&
377
+ !foundServerResponse
378
+ ) {
379
+ this.logger.trace(
380
+ "handleRedirectPromise - acquiring token from native platform"
381
+ );
382
+ const nativeClient = new NativeInteractionClient(
383
+ this.config,
384
+ this.browserStorage,
385
+ this.browserCrypto,
386
+ this.logger,
387
+ this.eventHandler,
388
+ this.navigationClient,
389
+ ApiId.handleRedirectPromise,
390
+ this.performanceClient,
391
+ this.nativeExtensionProvider,
392
+ request.accountId,
393
+ this.nativeInternalStorage,
394
+ request.correlationId
395
+ );
396
+ redirectResponse = nativeClient.handleRedirectPromise();
397
+ } else {
398
+ this.logger.trace(
399
+ "handleRedirectPromise - acquiring token from web flow"
400
+ );
401
+ const correlationId =
402
+ this.browserStorage.getTemporaryCache(
403
+ TemporaryCacheKeys.CORRELATION_ID,
404
+ true
405
+ ) || Constants.EMPTY_STRING;
406
+ const redirectClient =
407
+ this.createRedirectClient(correlationId);
408
+ redirectResponse =
409
+ redirectClient.handleRedirectPromise(
410
+ foundServerResponse
411
+ );
412
+ }
413
+
414
+ response = redirectResponse
415
+ .then((result: AuthenticationResult | null) => {
416
+ if (result) {
417
+ // Emit login event if number of accounts change
418
+
419
+ const isLoggingIn =
420
+ loggedInAccounts.length <
421
+ this.getAllAccounts().length;
422
+ if (isLoggingIn) {
423
+ this.eventHandler.emitEvent(
424
+ EventType.LOGIN_SUCCESS,
425
+ InteractionType.Redirect,
426
+ result
427
+ );
428
+ this.logger.verbose(
429
+ "handleRedirectResponse returned result, login success"
430
+ );
431
+ } else {
432
+ this.eventHandler.emitEvent(
433
+ EventType.ACQUIRE_TOKEN_SUCCESS,
434
+ InteractionType.Redirect,
435
+ result
436
+ );
437
+ this.logger.verbose(
438
+ "handleRedirectResponse returned result, acquire token success"
439
+ );
440
+ }
441
+ }
442
+ this.eventHandler.emitEvent(
443
+ EventType.HANDLE_REDIRECT_END,
444
+ InteractionType.Redirect
445
+ );
446
+
447
+ return result;
448
+ })
449
+ .catch((e) => {
450
+ // Emit login event if there is an account
451
+ if (loggedInAccounts.length > 0) {
452
+ this.eventHandler.emitEvent(
453
+ EventType.ACQUIRE_TOKEN_FAILURE,
454
+ InteractionType.Redirect,
455
+ null,
456
+ e as EventError
457
+ );
458
+ } else {
459
+ this.eventHandler.emitEvent(
460
+ EventType.LOGIN_FAILURE,
461
+ InteractionType.Redirect,
462
+ null,
463
+ e as EventError
464
+ );
465
+ }
466
+ this.eventHandler.emitEvent(
467
+ EventType.HANDLE_REDIRECT_END,
468
+ InteractionType.Redirect
469
+ );
470
+
471
+ throw e;
472
+ });
473
+ this.redirectResponse.set(redirectResponseKey, response);
474
+ } else {
475
+ this.logger.verbose(
476
+ "handleRedirectPromise has been called previously, returning the result from the first call"
477
+ );
478
+ }
479
+
480
+ return response;
481
+ }
482
+ this.logger.verbose(
483
+ "handleRedirectPromise returns null, not browser environment"
484
+ );
485
+ return null;
486
+ }
487
+
488
+ /**
489
+ * 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
490
+ * the page, so any code that follows this function will not execute.
491
+ *
492
+ * 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
493
+ * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
494
+ *
495
+ * @param request
496
+ */
497
+ async acquireTokenRedirect(request: RedirectRequest): Promise<void> {
498
+ // Preflight request
499
+ const correlationId = this.getRequestCorrelationId(request);
500
+ this.logger.verbose("acquireTokenRedirect called", correlationId);
501
+ this.preflightBrowserEnvironmentCheck(InteractionType.Redirect);
502
+
503
+ // If logged in, emit acquire token events
504
+ const isLoggedIn = this.getAllAccounts().length > 0;
505
+ if (isLoggedIn) {
506
+ this.eventHandler.emitEvent(
507
+ EventType.ACQUIRE_TOKEN_START,
508
+ InteractionType.Redirect,
509
+ request
510
+ );
511
+ } else {
512
+ this.eventHandler.emitEvent(
513
+ EventType.LOGIN_START,
514
+ InteractionType.Redirect,
515
+ request
516
+ );
517
+ }
518
+
519
+ let result: Promise<void>;
520
+
521
+ if (this.nativeExtensionProvider && this.canUseNative(request)) {
522
+ const nativeClient = new NativeInteractionClient(
523
+ this.config,
524
+ this.browserStorage,
525
+ this.browserCrypto,
526
+ this.logger,
527
+ this.eventHandler,
528
+ this.navigationClient,
529
+ ApiId.acquireTokenRedirect,
530
+ this.performanceClient,
531
+ this.nativeExtensionProvider,
532
+ this.getNativeAccountId(request),
533
+ this.nativeInternalStorage,
534
+ request.correlationId
535
+ );
536
+ result = nativeClient
537
+ .acquireTokenRedirect(request)
538
+ .catch((e: AuthError) => {
539
+ if (
540
+ e instanceof NativeAuthError &&
541
+ isFatalNativeAuthError(e)
542
+ ) {
543
+ this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
544
+ const redirectClient = this.createRedirectClient(
545
+ request.correlationId
546
+ );
547
+ return redirectClient.acquireToken(request);
548
+ } else if (e instanceof InteractionRequiredAuthError) {
549
+ this.logger.verbose(
550
+ "acquireTokenRedirect - Resolving interaction required error thrown by native broker by falling back to web flow"
551
+ );
552
+ const redirectClient = this.createRedirectClient(
553
+ request.correlationId
554
+ );
555
+ return redirectClient.acquireToken(request);
556
+ }
557
+ this.getBrowserStorage().setInteractionInProgress(false);
558
+ throw e;
559
+ });
560
+ } else {
561
+ const redirectClient = this.createRedirectClient(
562
+ request.correlationId
563
+ );
564
+ result = redirectClient.acquireToken(request);
565
+ }
566
+
567
+ return result.catch((e) => {
568
+ // If logged in, emit acquire token events
569
+ if (isLoggedIn) {
570
+ this.eventHandler.emitEvent(
571
+ EventType.ACQUIRE_TOKEN_FAILURE,
572
+ InteractionType.Redirect,
573
+ null,
574
+ e
575
+ );
576
+ } else {
577
+ this.eventHandler.emitEvent(
578
+ EventType.LOGIN_FAILURE,
579
+ InteractionType.Redirect,
580
+ null,
581
+ e
582
+ );
583
+ }
584
+ throw e;
585
+ });
586
+ }
587
+
588
+ // #endregion
589
+
590
+ // #region Popup Flow
591
+
592
+ /**
593
+ * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
594
+ *
595
+ * @param request
596
+ *
597
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
598
+ */
599
+ acquireTokenPopup(request: PopupRequest): Promise<AuthenticationResult> {
600
+ const correlationId = this.getRequestCorrelationId(request);
601
+ const atPopupMeasurement = this.performanceClient.startMeasurement(
602
+ PerformanceEvents.AcquireTokenPopup,
603
+ correlationId
604
+ );
605
+
606
+ try {
607
+ this.logger.verbose("acquireTokenPopup called", correlationId);
608
+ this.preflightBrowserEnvironmentCheck(InteractionType.Popup);
609
+ } catch (e) {
610
+ // Since this function is syncronous we need to reject
611
+ return Promise.reject(e);
612
+ }
613
+
614
+ // If logged in, emit acquire token events
615
+ const loggedInAccounts = this.getAllAccounts();
616
+ if (loggedInAccounts.length > 0) {
617
+ this.eventHandler.emitEvent(
618
+ EventType.ACQUIRE_TOKEN_START,
619
+ InteractionType.Popup,
620
+ request
621
+ );
622
+ } else {
623
+ this.eventHandler.emitEvent(
624
+ EventType.LOGIN_START,
625
+ InteractionType.Popup,
626
+ request
627
+ );
628
+ }
629
+
630
+ let result: Promise<AuthenticationResult>;
631
+
632
+ if (this.canUseNative(request)) {
633
+ result = this.acquireTokenNative(request, ApiId.acquireTokenPopup)
634
+ .then((response) => {
635
+ this.getBrowserStorage().setInteractionInProgress(false);
636
+ atPopupMeasurement.end({
637
+ success: true,
638
+ isNativeBroker: true,
639
+ requestId: response.requestId,
640
+ });
641
+ return response;
642
+ })
643
+ .catch((e: AuthError) => {
644
+ if (
645
+ e instanceof NativeAuthError &&
646
+ isFatalNativeAuthError(e)
647
+ ) {
648
+ this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
649
+ const popupClient = this.createPopupClient(
650
+ request.correlationId
651
+ );
652
+ return popupClient.acquireToken(request);
653
+ } else if (e instanceof InteractionRequiredAuthError) {
654
+ this.logger.verbose(
655
+ "acquireTokenPopup - Resolving interaction required error thrown by native broker by falling back to web flow"
656
+ );
657
+ const popupClient = this.createPopupClient(
658
+ request.correlationId
659
+ );
660
+ return popupClient.acquireToken(request);
661
+ }
662
+ this.getBrowserStorage().setInteractionInProgress(false);
663
+ throw e;
664
+ });
665
+ } else {
666
+ const popupClient = this.createPopupClient(request.correlationId);
667
+ result = popupClient.acquireToken(request);
668
+ }
669
+
670
+ return result
671
+ .then((result) => {
672
+ /*
673
+ * If logged in, emit acquire token events
674
+ */
675
+ const isLoggingIn =
676
+ loggedInAccounts.length < this.getAllAccounts().length;
677
+ if (isLoggingIn) {
678
+ this.eventHandler.emitEvent(
679
+ EventType.LOGIN_SUCCESS,
680
+ InteractionType.Popup,
681
+ result
682
+ );
683
+ } else {
684
+ this.eventHandler.emitEvent(
685
+ EventType.ACQUIRE_TOKEN_SUCCESS,
686
+ InteractionType.Popup,
687
+ result
688
+ );
689
+ }
690
+
691
+ atPopupMeasurement.add({
692
+ accessTokenSize: result.accessToken.length,
693
+ idTokenSize: result.idToken.length,
694
+ });
695
+ atPopupMeasurement.end({
696
+ success: true,
697
+ requestId: result.requestId,
698
+ });
699
+ return result;
700
+ })
701
+ .catch((e: AuthError) => {
702
+ if (loggedInAccounts.length > 0) {
703
+ this.eventHandler.emitEvent(
704
+ EventType.ACQUIRE_TOKEN_FAILURE,
705
+ InteractionType.Popup,
706
+ null,
707
+ e
708
+ );
709
+ } else {
710
+ this.eventHandler.emitEvent(
711
+ EventType.LOGIN_FAILURE,
712
+ InteractionType.Popup,
713
+ null,
714
+ e
715
+ );
716
+ }
717
+
718
+ atPopupMeasurement.end({
719
+ errorCode: e.errorCode,
720
+ subErrorCode: e.subError,
721
+ success: false,
722
+ });
723
+ // Since this function is syncronous we need to reject
724
+ return Promise.reject(e);
725
+ });
726
+ }
727
+
728
+ private trackPageVisibilityWithMeasurement(): void {
729
+ const measurement =
730
+ this.ssoSilentMeasurement ||
731
+ this.acquireTokenByCodeAsyncMeasurement;
732
+ if (!measurement) {
733
+ return;
734
+ }
735
+
736
+ this.logger.info(
737
+ "Perf: Visibility change detected in ",
738
+ measurement.event.name
739
+ );
740
+ measurement.increment({
741
+ visibilityChangeCount: 1,
742
+ });
743
+ }
744
+ // #endregion
745
+
746
+ // #region Silent Flow
747
+
748
+ /**
749
+ * This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
750
+ * - Any browser using a form of Intelligent Tracking Prevention
751
+ * - If there is not an established session with the service
752
+ *
753
+ * In these cases, the request must be done inside a popup or full frame redirect.
754
+ *
755
+ * For the cases where interaction is required, you cannot send a request with prompt=none.
756
+ *
757
+ * If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
758
+ * you session on the server still exists.
759
+ * @param request {@link SsoSilentRequest}
760
+ *
761
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
762
+ */
763
+ async ssoSilent(request: SsoSilentRequest): Promise<AuthenticationResult> {
764
+ const correlationId = this.getRequestCorrelationId(request);
765
+ const validRequest = {
766
+ ...request,
767
+ // will be PromptValue.NONE or PromptValue.NO_SESSION
768
+ prompt: request.prompt,
769
+ correlationId: correlationId,
770
+ };
771
+ this.preflightBrowserEnvironmentCheck(InteractionType.Silent);
772
+ this.ssoSilentMeasurement = this.performanceClient.startMeasurement(
773
+ PerformanceEvents.SsoSilent,
774
+ correlationId
775
+ );
776
+ this.ssoSilentMeasurement?.increment({
777
+ visibilityChangeCount: 0,
778
+ });
779
+ document.addEventListener(
780
+ "visibilitychange",
781
+ this.trackPageVisibilityWithMeasurement
782
+ );
783
+ this.logger.verbose("ssoSilent called", correlationId);
784
+ this.eventHandler.emitEvent(
785
+ EventType.SSO_SILENT_START,
786
+ InteractionType.Silent,
787
+ validRequest
788
+ );
789
+
790
+ let result: Promise<AuthenticationResult>;
791
+
792
+ if (this.canUseNative(validRequest)) {
793
+ result = this.acquireTokenNative(
794
+ validRequest,
795
+ ApiId.ssoSilent
796
+ ).catch((e: AuthError) => {
797
+ // If native token acquisition fails for availability reasons fallback to standard flow
798
+ if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
799
+ this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
800
+ const silentIframeClient = this.createSilentIframeClient(
801
+ validRequest.correlationId
802
+ );
803
+ return silentIframeClient.acquireToken(validRequest);
804
+ }
805
+ throw e;
806
+ });
807
+ } else {
808
+ const silentIframeClient = this.createSilentIframeClient(
809
+ validRequest.correlationId
810
+ );
811
+ result = silentIframeClient.acquireToken(validRequest);
812
+ }
813
+
814
+ return result
815
+ .then((response) => {
816
+ this.eventHandler.emitEvent(
817
+ EventType.SSO_SILENT_SUCCESS,
818
+ InteractionType.Silent,
819
+ response
820
+ );
821
+ this.ssoSilentMeasurement?.add({
822
+ accessTokenSize: response.accessToken.length,
823
+ idTokenSize: response.idToken.length,
824
+ });
825
+ this.ssoSilentMeasurement?.end({
826
+ success: true,
827
+ isNativeBroker: response.fromNativeBroker,
828
+ requestId: response.requestId,
829
+ });
830
+ return response;
831
+ })
832
+ .catch((e: AuthError) => {
833
+ this.eventHandler.emitEvent(
834
+ EventType.SSO_SILENT_FAILURE,
835
+ InteractionType.Silent,
836
+ null,
837
+ e
838
+ );
839
+ this.ssoSilentMeasurement?.end({
840
+ errorCode: e.errorCode,
841
+ subErrorCode: e.subError,
842
+ success: false,
843
+ });
844
+ throw e;
845
+ })
846
+ .finally(() => {
847
+ document.removeEventListener(
848
+ "visibilitychange",
849
+ this.trackPageVisibilityWithMeasurement
850
+ );
851
+ });
852
+ }
853
+
854
+ /**
855
+ * This function redeems an authorization code (passed as code) from the eSTS token endpoint.
856
+ * This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
857
+ * This API is not indended for normal authorization code acquisition and redemption.
858
+ *
859
+ * Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
860
+ *
861
+ * @param request {@link AuthorizationCodeRequest}
862
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
863
+ */
864
+ async acquireTokenByCode(
865
+ request: AuthorizationCodeRequest
866
+ ): Promise<AuthenticationResult> {
867
+ const correlationId = this.getRequestCorrelationId(request);
868
+ this.preflightBrowserEnvironmentCheck(InteractionType.Silent);
869
+ this.logger.trace("acquireTokenByCode called", correlationId);
870
+ this.eventHandler.emitEvent(
871
+ EventType.ACQUIRE_TOKEN_BY_CODE_START,
872
+ InteractionType.Silent,
873
+ request
874
+ );
875
+ const atbcMeasurement = this.performanceClient.startMeasurement(
876
+ PerformanceEvents.AcquireTokenByCode,
877
+ request.correlationId
878
+ );
879
+
880
+ try {
881
+ if (request.code && request.nativeAccountId) {
882
+ // Throw error in case server returns both spa_code and spa_accountid in exchange for auth code.
883
+ throw createBrowserAuthError(
884
+ BrowserAuthErrorCodes.spaCodeAndNativeAccountIdPresent
885
+ );
886
+ } else if (request.code) {
887
+ const hybridAuthCode = request.code;
888
+ let response = this.hybridAuthCodeResponses.get(hybridAuthCode);
889
+ if (!response) {
890
+ this.logger.verbose(
891
+ "Initiating new acquireTokenByCode request",
892
+ correlationId
893
+ );
894
+ response = this.acquireTokenByCodeAsync({
895
+ ...request,
896
+ correlationId,
897
+ })
898
+ .then((result: AuthenticationResult) => {
899
+ this.eventHandler.emitEvent(
900
+ EventType.ACQUIRE_TOKEN_BY_CODE_SUCCESS,
901
+ InteractionType.Silent,
902
+ result
903
+ );
904
+ this.hybridAuthCodeResponses.delete(hybridAuthCode);
905
+ atbcMeasurement.add({
906
+ accessTokenSize: result.accessToken.length,
907
+ idTokenSize: result.idToken.length,
908
+ });
909
+ atbcMeasurement.end({
910
+ success: true,
911
+ isNativeBroker: result.fromNativeBroker,
912
+ requestId: result.requestId,
913
+ });
914
+ return result;
915
+ })
916
+ .catch((error: AuthError) => {
917
+ this.hybridAuthCodeResponses.delete(hybridAuthCode);
918
+ this.eventHandler.emitEvent(
919
+ EventType.ACQUIRE_TOKEN_BY_CODE_FAILURE,
920
+ InteractionType.Silent,
921
+ null,
922
+ error
923
+ );
924
+ atbcMeasurement.end({
925
+ errorCode: error.errorCode,
926
+ subErrorCode: error.subError,
927
+ success: false,
928
+ });
929
+ throw error;
930
+ });
931
+ this.hybridAuthCodeResponses.set(hybridAuthCode, response);
932
+ } else {
933
+ this.logger.verbose(
934
+ "Existing acquireTokenByCode request found",
935
+ request.correlationId
936
+ );
937
+ atbcMeasurement.discard();
938
+ }
939
+ return response;
940
+ } else if (request.nativeAccountId) {
941
+ if (this.canUseNative(request, request.nativeAccountId)) {
942
+ return this.acquireTokenNative(
943
+ request,
944
+ ApiId.acquireTokenByCode,
945
+ request.nativeAccountId
946
+ ).catch((e: AuthError) => {
947
+ // If native token acquisition fails for availability reasons fallback to standard flow
948
+ if (
949
+ e instanceof NativeAuthError &&
950
+ isFatalNativeAuthError(e)
951
+ ) {
952
+ this.nativeExtensionProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
953
+ }
954
+ throw e;
955
+ });
956
+ } else {
957
+ throw createBrowserAuthError(
958
+ BrowserAuthErrorCodes.unableToAcquireTokenFromNativePlatform
959
+ );
960
+ }
961
+ } else {
962
+ throw createBrowserAuthError(
963
+ BrowserAuthErrorCodes.authCodeOrNativeAccountIdRequired
964
+ );
965
+ }
966
+ } catch (e) {
967
+ this.eventHandler.emitEvent(
968
+ EventType.ACQUIRE_TOKEN_BY_CODE_FAILURE,
969
+ InteractionType.Silent,
970
+ null,
971
+ e as EventError
972
+ );
973
+ atbcMeasurement.end({
974
+ errorCode: (e instanceof AuthError && e.errorCode) || undefined,
975
+ subErrorCode:
976
+ (e instanceof AuthError && e.subError) || undefined,
977
+ success: false,
978
+ });
979
+ throw e;
980
+ }
981
+ }
982
+
983
+ /**
984
+ * Creates a SilentAuthCodeClient to redeem an authorization code.
985
+ * @param request
986
+ * @returns Result of the operation to redeem the authorization code
987
+ */
988
+ private async acquireTokenByCodeAsync(
989
+ request: AuthorizationCodeRequest
990
+ ): Promise<AuthenticationResult> {
991
+ this.logger.trace(
992
+ "acquireTokenByCodeAsync called",
993
+ request.correlationId
994
+ );
995
+ this.acquireTokenByCodeAsyncMeasurement =
996
+ this.performanceClient.startMeasurement(
997
+ PerformanceEvents.AcquireTokenByCodeAsync,
998
+ request.correlationId
999
+ );
1000
+ this.acquireTokenByCodeAsyncMeasurement?.increment({
1001
+ visibilityChangeCount: 0,
1002
+ });
1003
+ document.addEventListener(
1004
+ "visibilitychange",
1005
+ this.trackPageVisibilityWithMeasurement
1006
+ );
1007
+ const silentAuthCodeClient = this.createSilentAuthCodeClient(
1008
+ request.correlationId
1009
+ );
1010
+ const silentTokenResult = await silentAuthCodeClient
1011
+ .acquireToken(request)
1012
+ .then((response) => {
1013
+ this.acquireTokenByCodeAsyncMeasurement?.end({
1014
+ success: true,
1015
+ fromCache: response.fromCache,
1016
+ isNativeBroker: response.fromNativeBroker,
1017
+ requestId: response.requestId,
1018
+ });
1019
+ return response;
1020
+ })
1021
+ .catch((tokenRenewalError: AuthError) => {
1022
+ this.acquireTokenByCodeAsyncMeasurement?.end({
1023
+ errorCode: tokenRenewalError.errorCode,
1024
+ subErrorCode: tokenRenewalError.subError,
1025
+ success: false,
1026
+ });
1027
+ throw tokenRenewalError;
1028
+ })
1029
+ .finally(() => {
1030
+ document.removeEventListener(
1031
+ "visibilitychange",
1032
+ this.trackPageVisibilityWithMeasurement
1033
+ );
1034
+ });
1035
+ return silentTokenResult;
1036
+ }
1037
+
1038
+ /**
1039
+ * Attempt to acquire an access token from the cache
1040
+ * @param silentCacheClient SilentCacheClient
1041
+ * @param commonRequest CommonSilentFlowRequest
1042
+ * @param silentRequest SilentRequest
1043
+ * @returns A promise that, when resolved, returns the access token
1044
+ */
1045
+ protected async acquireTokenFromCache(
1046
+ silentCacheClient: SilentCacheClient,
1047
+ commonRequest: CommonSilentFlowRequest,
1048
+ silentRequest: SilentRequest
1049
+ ): Promise<AuthenticationResult> {
1050
+ this.performanceClient.addQueueMeasurement(
1051
+ PerformanceEvents.AcquireTokenFromCache,
1052
+ commonRequest.correlationId
1053
+ );
1054
+ switch (silentRequest.cacheLookupPolicy) {
1055
+ case CacheLookupPolicy.Default:
1056
+ case CacheLookupPolicy.AccessToken:
1057
+ case CacheLookupPolicy.AccessTokenAndRefreshToken:
1058
+ return invokeAsync(
1059
+ silentCacheClient.acquireToken.bind(silentCacheClient),
1060
+ PerformanceEvents.SilentCacheClientAcquireToken,
1061
+ this.logger,
1062
+ this.performanceClient,
1063
+ commonRequest.correlationId
1064
+ )(commonRequest);
1065
+ default:
1066
+ throw createClientAuthError(
1067
+ ClientAuthErrorCodes.tokenRefreshRequired
1068
+ );
1069
+ }
1070
+ }
1071
+
1072
+ /**
1073
+ * Attempt to acquire an access token via a refresh token
1074
+ * @param commonRequest CommonSilentFlowRequest
1075
+ * @param silentRequest SilentRequest
1076
+ * @returns A promise that, when resolved, returns the access token
1077
+ */
1078
+ public async acquireTokenByRefreshToken(
1079
+ commonRequest: CommonSilentFlowRequest,
1080
+ silentRequest: SilentRequest
1081
+ ): Promise<AuthenticationResult> {
1082
+ this.performanceClient.addQueueMeasurement(
1083
+ PerformanceEvents.AcquireTokenByRefreshToken,
1084
+ commonRequest.correlationId
1085
+ );
1086
+ switch (silentRequest.cacheLookupPolicy) {
1087
+ case CacheLookupPolicy.Default:
1088
+ case CacheLookupPolicy.AccessTokenAndRefreshToken:
1089
+ case CacheLookupPolicy.RefreshToken:
1090
+ case CacheLookupPolicy.RefreshTokenAndNetwork:
1091
+ const silentRefreshClient = this.createSilentRefreshClient(
1092
+ commonRequest.correlationId
1093
+ );
1094
+
1095
+ return invokeAsync(
1096
+ silentRefreshClient.acquireToken.bind(silentRefreshClient),
1097
+ PerformanceEvents.SilentRefreshClientAcquireToken,
1098
+ this.logger,
1099
+ this.performanceClient,
1100
+ commonRequest.correlationId
1101
+ )(commonRequest);
1102
+ default:
1103
+ throw createClientAuthError(
1104
+ ClientAuthErrorCodes.tokenRefreshRequired
1105
+ );
1106
+ }
1107
+ }
1108
+
1109
+ /**
1110
+ * Attempt to acquire an access token via an iframe
1111
+ * @param request CommonSilentFlowRequest
1112
+ * @returns A promise that, when resolved, returns the access token
1113
+ */
1114
+ protected async acquireTokenBySilentIframe(
1115
+ request: CommonSilentFlowRequest
1116
+ ): Promise<AuthenticationResult> {
1117
+ this.performanceClient.addQueueMeasurement(
1118
+ PerformanceEvents.AcquireTokenBySilentIframe,
1119
+ request.correlationId
1120
+ );
1121
+
1122
+ const silentIframeClient = this.createSilentIframeClient(
1123
+ request.correlationId
1124
+ );
1125
+
1126
+ return invokeAsync(
1127
+ silentIframeClient.acquireToken.bind(silentIframeClient),
1128
+ PerformanceEvents.SilentIframeClientAcquireToken,
1129
+ this.logger,
1130
+ this.performanceClient,
1131
+ request.correlationId
1132
+ )(request);
1133
+ }
1134
+
1135
+ // #endregion
1136
+
1137
+ // #region Logout
1138
+
1139
+ /**
1140
+ * Deprecated logout function. Use logoutRedirect or logoutPopup instead
1141
+ * @param logoutRequest
1142
+ * @deprecated
1143
+ */
1144
+ async logout(logoutRequest?: EndSessionRequest): Promise<void> {
1145
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
1146
+ this.logger.warning(
1147
+ "logout API is deprecated and will be removed in msal-browser v3.0.0. Use logoutRedirect instead.",
1148
+ correlationId
1149
+ );
1150
+ return this.logoutRedirect({
1151
+ correlationId,
1152
+ ...logoutRequest,
1153
+ });
1154
+ }
1155
+
1156
+ /**
1157
+ * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
1158
+ * Default behaviour is to redirect the user to `window.location.href`.
1159
+ * @param logoutRequest
1160
+ */
1161
+ async logoutRedirect(logoutRequest?: EndSessionRequest): Promise<void> {
1162
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
1163
+ this.preflightBrowserEnvironmentCheck(InteractionType.Redirect);
1164
+
1165
+ const redirectClient = this.createRedirectClient(correlationId);
1166
+ return redirectClient.logout(logoutRequest);
1167
+ }
1168
+
1169
+ /**
1170
+ * Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
1171
+ * @param logoutRequest
1172
+ */
1173
+ logoutPopup(logoutRequest?: EndSessionPopupRequest): Promise<void> {
1174
+ try {
1175
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
1176
+ this.preflightBrowserEnvironmentCheck(InteractionType.Popup);
1177
+ const popupClient = this.createPopupClient(correlationId);
1178
+ return popupClient.logout(logoutRequest);
1179
+ } catch (e) {
1180
+ // Since this function is syncronous we need to reject
1181
+ return Promise.reject(e);
1182
+ }
1183
+ }
1184
+
1185
+ /**
1186
+ * Creates a cache interaction client to clear broswer cache.
1187
+ * @param logoutRequest
1188
+ */
1189
+ async clearCache(logoutRequest?: ClearCacheRequest): Promise<void> {
1190
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
1191
+ const cacheClient = this.createSilentCacheClient(correlationId);
1192
+ return cacheClient.logout(logoutRequest);
1193
+ }
1194
+
1195
+ // #endregion
1196
+
1197
+ // #region Account APIs
1198
+
1199
+ /**
1200
+ * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
1201
+ * @param accountFilter - (Optional) filter to narrow down the accounts returned
1202
+ * @returns Array of AccountInfo objects in cache
1203
+ */
1204
+ getAllAccounts(accountFilter?: AccountFilter): AccountInfo[] {
1205
+ this.logger.verbose("getAllAccounts called");
1206
+ return this.isBrowserEnvironment
1207
+ ? this.browserStorage.getAllAccounts(accountFilter)
1208
+ : [];
1209
+ }
1210
+
1211
+ /**
1212
+ * Returns the first account found in the cache that matches the account filter passed in.
1213
+ * @param accountFilter
1214
+ * @returns The first account found in the cache matching the provided filter or null if no account could be found.
1215
+ */
1216
+ getAccount(accountFilter: AccountFilter): AccountInfo | null {
1217
+ this.logger.trace("getAccount called");
1218
+ if (Object.keys(accountFilter).length === 0) {
1219
+ this.logger.warning("getAccount: No accountFilter provided");
1220
+ return null;
1221
+ }
1222
+
1223
+ const account: AccountInfo | null =
1224
+ this.browserStorage.getAccountInfoFilteredBy(accountFilter);
1225
+
1226
+ if (account) {
1227
+ this.logger.verbose(
1228
+ "getAccount: Account matching provided filter found, returning"
1229
+ );
1230
+ return account;
1231
+ } else {
1232
+ this.logger.verbose(
1233
+ "getAccount: No matching account found, returning null"
1234
+ );
1235
+ return null;
1236
+ }
1237
+ }
1238
+
1239
+ /**
1240
+ * Returns the signed in account matching username.
1241
+ * (the account object is created at the time of successful login)
1242
+ * or null when no matching account is found.
1243
+ * This API is provided for convenience but getAccountById should be used for best reliability
1244
+ * @param username
1245
+ * @returns The account object stored in MSAL
1246
+ */
1247
+ getAccountByUsername(username: string): AccountInfo | null {
1248
+ this.logger.trace("getAccountByUsername called");
1249
+ if (!username) {
1250
+ this.logger.warning("getAccountByUsername: No username provided");
1251
+ return null;
1252
+ }
1253
+
1254
+ const account = this.browserStorage.getAccountInfoFilteredBy({
1255
+ username,
1256
+ });
1257
+ if (account) {
1258
+ this.logger.verbose(
1259
+ "getAccountByUsername: Account matching username found, returning"
1260
+ );
1261
+ this.logger.verbosePii(
1262
+ `getAccountByUsername: Returning signed-in accounts matching username: ${username}`
1263
+ );
1264
+ return account;
1265
+ } else {
1266
+ this.logger.verbose(
1267
+ "getAccountByUsername: No matching account found, returning null"
1268
+ );
1269
+ return null;
1270
+ }
1271
+ }
1272
+
1273
+ /**
1274
+ * Returns the signed in account matching homeAccountId.
1275
+ * (the account object is created at the time of successful login)
1276
+ * or null when no matching account is found
1277
+ * @param homeAccountId
1278
+ * @returns The account object stored in MSAL
1279
+ */
1280
+ getAccountByHomeId(homeAccountId: string): AccountInfo | null {
1281
+ this.logger.trace("getAccountByHomeId called");
1282
+ if (!homeAccountId) {
1283
+ this.logger.warning(
1284
+ "getAccountByHomeId: No homeAccountId provided"
1285
+ );
1286
+ return null;
1287
+ }
1288
+
1289
+ const account = this.browserStorage.getAccountInfoFilteredBy({
1290
+ homeAccountId,
1291
+ });
1292
+ if (account) {
1293
+ this.logger.verbose(
1294
+ "getAccountByHomeId: Account matching homeAccountId found, returning"
1295
+ );
1296
+ this.logger.verbosePii(
1297
+ `getAccountByHomeId: Returning signed-in accounts matching homeAccountId: ${homeAccountId}`
1298
+ );
1299
+ return account;
1300
+ } else {
1301
+ this.logger.verbose(
1302
+ "getAccountByHomeId: No matching account found, returning null"
1303
+ );
1304
+ return null;
1305
+ }
1306
+ }
1307
+
1308
+ /**
1309
+ * Returns the signed in account matching localAccountId.
1310
+ * (the account object is created at the time of successful login)
1311
+ * or null when no matching account is found
1312
+ * @param localAccountId
1313
+ * @returns The account object stored in MSAL
1314
+ */
1315
+ getAccountByLocalId(localAccountId: string): AccountInfo | null {
1316
+ this.logger.trace("getAccountByLocalId called");
1317
+ if (!localAccountId) {
1318
+ this.logger.warning(
1319
+ "getAccountByLocalId: No localAccountId provided"
1320
+ );
1321
+ return null;
1322
+ }
1323
+
1324
+ const account = this.browserStorage.getAccountInfoFilteredBy({
1325
+ localAccountId,
1326
+ });
1327
+ if (account) {
1328
+ this.logger.verbose(
1329
+ "getAccountByLocalId: Account matching localAccountId found, returning"
1330
+ );
1331
+ this.logger.verbosePii(
1332
+ `getAccountByLocalId: Returning signed-in accounts matching localAccountId: ${localAccountId}`
1333
+ );
1334
+ return account;
1335
+ } else {
1336
+ this.logger.verbose(
1337
+ "getAccountByLocalId: No matching account found, returning null"
1338
+ );
1339
+ return null;
1340
+ }
1341
+ }
1342
+
1343
+ /**
1344
+ * 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.
1345
+ * @param account
1346
+ */
1347
+ setActiveAccount(account: AccountInfo | null): void {
1348
+ this.browserStorage.setActiveAccount(account);
1349
+ }
1350
+
1351
+ /**
1352
+ * Gets the currently active account
1353
+ */
1354
+ getActiveAccount(): AccountInfo | null {
1355
+ return this.browserStorage.getActiveAccount();
1356
+ }
1357
+
1358
+ // #endregion
1359
+
1360
+ /**
1361
+ * Hydrates the cache with the tokens from an AuthenticationResult
1362
+ * @param result
1363
+ * @param request
1364
+ * @returns
1365
+ */
1366
+ async hydrateCache(
1367
+ result: AuthenticationResult,
1368
+ request:
1369
+ | SilentRequest
1370
+ | SsoSilentRequest
1371
+ | RedirectRequest
1372
+ | PopupRequest
1373
+ ): Promise<void> {
1374
+ this.logger.verbose("hydrateCache called");
1375
+
1376
+ // Account gets saved to browser storage regardless of native or not
1377
+ const accountEntity = AccountEntity.createFromAccountInfo(
1378
+ result.account,
1379
+ result.cloudGraphHostName,
1380
+ result.msGraphHost
1381
+ );
1382
+ this.browserStorage.setAccount(accountEntity);
1383
+
1384
+ if (result.fromNativeBroker) {
1385
+ this.logger.verbose(
1386
+ "Response was from native broker, storing in-memory"
1387
+ );
1388
+ // Tokens from native broker are stored in-memory
1389
+ return this.nativeInternalStorage.hydrateCache(result, request);
1390
+ } else {
1391
+ return this.browserStorage.hydrateCache(result, request);
1392
+ }
1393
+ }
1394
+
1395
+ // #region Helpers
1396
+
1397
+ /**
1398
+ * Helper to validate app environment before making an auth request
1399
+ *
1400
+ * @protected
1401
+ * @param {InteractionType} interactionType What kind of interaction is being used
1402
+ * @param {boolean} [isAppEmbedded=false] Whether to set interaction in progress temp cache flag
1403
+ */
1404
+ public preflightBrowserEnvironmentCheck(
1405
+ interactionType: InteractionType,
1406
+ isAppEmbedded: boolean = false
1407
+ ): void {
1408
+ this.logger.verbose("preflightBrowserEnvironmentCheck started");
1409
+ // Block request if not in browser environment
1410
+ BrowserUtils.blockNonBrowserEnvironment(this.isBrowserEnvironment);
1411
+
1412
+ // Block redirects if in an iframe
1413
+ BrowserUtils.blockRedirectInIframe(
1414
+ interactionType,
1415
+ this.config.system.allowRedirectInIframe
1416
+ );
1417
+
1418
+ // Block auth requests inside a hidden iframe
1419
+ BrowserUtils.blockReloadInHiddenIframes();
1420
+
1421
+ // Block redirectUri opened in a popup from calling MSAL APIs
1422
+ BrowserUtils.blockAcquireTokenInPopups();
1423
+
1424
+ // Block token acquisition before initialize has been called
1425
+ BrowserUtils.blockAPICallsBeforeInitialize(this.initialized);
1426
+
1427
+ // Block redirects if memory storage is enabled but storeAuthStateInCookie is not
1428
+ if (
1429
+ interactionType === InteractionType.Redirect &&
1430
+ this.config.cache.cacheLocation ===
1431
+ BrowserCacheLocation.MemoryStorage &&
1432
+ !this.config.cache.storeAuthStateInCookie
1433
+ ) {
1434
+ throw createBrowserConfigurationAuthError(
1435
+ BrowserConfigurationAuthErrorCodes.inMemRedirectUnavailable
1436
+ );
1437
+ }
1438
+
1439
+ if (
1440
+ interactionType === InteractionType.Redirect ||
1441
+ interactionType === InteractionType.Popup
1442
+ ) {
1443
+ this.preflightInteractiveRequest(!isAppEmbedded);
1444
+ }
1445
+ }
1446
+
1447
+ /**
1448
+ * Preflight check for interactive requests
1449
+ *
1450
+ * @protected
1451
+ * @param {boolean} setInteractionInProgress Whether to set interaction in progress temp cache flag
1452
+ */
1453
+ protected preflightInteractiveRequest(
1454
+ setInteractionInProgress: boolean
1455
+ ): void {
1456
+ this.logger.verbose(
1457
+ "preflightInteractiveRequest called, validating app environment"
1458
+ );
1459
+ // block the reload if it occurred inside a hidden iframe
1460
+ BrowserUtils.blockReloadInHiddenIframes();
1461
+
1462
+ // Set interaction in progress temporary cache or throw if alread set.
1463
+ if (setInteractionInProgress) {
1464
+ this.getBrowserStorage().setInteractionInProgress(true);
1465
+ }
1466
+ }
1467
+
1468
+ /**
1469
+ * Acquire a token from native device (e.g. WAM)
1470
+ * @param request
1471
+ */
1472
+ public async acquireTokenNative(
1473
+ request: PopupRequest | SilentRequest | SsoSilentRequest,
1474
+ apiId: ApiId,
1475
+ accountId?: string
1476
+ ): Promise<AuthenticationResult> {
1477
+ this.logger.trace("acquireTokenNative called");
1478
+ if (!this.nativeExtensionProvider) {
1479
+ throw createBrowserAuthError(
1480
+ BrowserAuthErrorCodes.nativeConnectionNotEstablished
1481
+ );
1482
+ }
1483
+
1484
+ const nativeClient = new NativeInteractionClient(
1485
+ this.config,
1486
+ this.browserStorage,
1487
+ this.browserCrypto,
1488
+ this.logger,
1489
+ this.eventHandler,
1490
+ this.navigationClient,
1491
+ apiId,
1492
+ this.performanceClient,
1493
+ this.nativeExtensionProvider,
1494
+ accountId || this.getNativeAccountId(request),
1495
+ this.nativeInternalStorage,
1496
+ request.correlationId
1497
+ );
1498
+
1499
+ return nativeClient.acquireToken(request);
1500
+ }
1501
+
1502
+ /**
1503
+ * Returns boolean indicating if this request can use the native broker
1504
+ * @param request
1505
+ */
1506
+ public canUseNative(
1507
+ request: RedirectRequest | PopupRequest | SsoSilentRequest,
1508
+ accountId?: string
1509
+ ): boolean {
1510
+ this.logger.trace("canUseNative called");
1511
+ if (
1512
+ !NativeMessageHandler.isNativeAvailable(
1513
+ this.config,
1514
+ this.logger,
1515
+ this.nativeExtensionProvider,
1516
+ request.authenticationScheme
1517
+ )
1518
+ ) {
1519
+ this.logger.trace(
1520
+ "canUseNative: isNativeAvailable returned false, returning false"
1521
+ );
1522
+ return false;
1523
+ }
1524
+
1525
+ if (request.prompt) {
1526
+ switch (request.prompt) {
1527
+ case PromptValue.NONE:
1528
+ case PromptValue.CONSENT:
1529
+ case PromptValue.LOGIN:
1530
+ this.logger.trace(
1531
+ "canUseNative: prompt is compatible with native flow"
1532
+ );
1533
+ break;
1534
+ default:
1535
+ this.logger.trace(
1536
+ `canUseNative: prompt = ${request.prompt} is not compatible with native flow, returning false`
1537
+ );
1538
+ return false;
1539
+ }
1540
+ }
1541
+
1542
+ if (!accountId && !this.getNativeAccountId(request)) {
1543
+ this.logger.trace(
1544
+ "canUseNative: nativeAccountId is not available, returning false"
1545
+ );
1546
+ return false;
1547
+ }
1548
+
1549
+ return true;
1550
+ }
1551
+
1552
+ /**
1553
+ * Get the native accountId from the account
1554
+ * @param request
1555
+ * @returns
1556
+ */
1557
+ public getNativeAccountId(
1558
+ request: RedirectRequest | PopupRequest | SsoSilentRequest
1559
+ ): string {
1560
+ const account =
1561
+ request.account ||
1562
+ this.browserStorage.getAccountInfoByHints(
1563
+ request.loginHint,
1564
+ request.sid
1565
+ ) ||
1566
+ this.getActiveAccount();
1567
+
1568
+ return (account && account.nativeAccountId) || "";
1569
+ }
1570
+
1571
+ /**
1572
+ * Returns new instance of the Popup Interaction Client
1573
+ * @param correlationId
1574
+ */
1575
+ public createPopupClient(correlationId?: string): PopupClient {
1576
+ return new PopupClient(
1577
+ this.config,
1578
+ this.browserStorage,
1579
+ this.browserCrypto,
1580
+ this.logger,
1581
+ this.eventHandler,
1582
+ this.navigationClient,
1583
+ this.performanceClient,
1584
+ this.nativeInternalStorage,
1585
+ this.nativeExtensionProvider,
1586
+ correlationId
1587
+ );
1588
+ }
1589
+
1590
+ /**
1591
+ * Returns new instance of the Redirect Interaction Client
1592
+ * @param correlationId
1593
+ */
1594
+ protected createRedirectClient(correlationId?: string): RedirectClient {
1595
+ return new RedirectClient(
1596
+ this.config,
1597
+ this.browserStorage,
1598
+ this.browserCrypto,
1599
+ this.logger,
1600
+ this.eventHandler,
1601
+ this.navigationClient,
1602
+ this.performanceClient,
1603
+ this.nativeInternalStorage,
1604
+ this.nativeExtensionProvider,
1605
+ correlationId
1606
+ );
1607
+ }
1608
+
1609
+ /**
1610
+ * Returns new instance of the Silent Iframe Interaction Client
1611
+ * @param correlationId
1612
+ */
1613
+ public createSilentIframeClient(
1614
+ correlationId?: string
1615
+ ): SilentIframeClient {
1616
+ return new SilentIframeClient(
1617
+ this.config,
1618
+ this.browserStorage,
1619
+ this.browserCrypto,
1620
+ this.logger,
1621
+ this.eventHandler,
1622
+ this.navigationClient,
1623
+ ApiId.ssoSilent,
1624
+ this.performanceClient,
1625
+ this.nativeInternalStorage,
1626
+ this.nativeExtensionProvider,
1627
+ correlationId
1628
+ );
1629
+ }
1630
+
1631
+ /**
1632
+ * Returns new instance of the Silent Cache Interaction Client
1633
+ */
1634
+ protected createSilentCacheClient(
1635
+ correlationId?: string
1636
+ ): SilentCacheClient {
1637
+ return new SilentCacheClient(
1638
+ this.config,
1639
+ this.browserStorage,
1640
+ this.browserCrypto,
1641
+ this.logger,
1642
+ this.eventHandler,
1643
+ this.navigationClient,
1644
+ this.performanceClient,
1645
+ this.nativeExtensionProvider,
1646
+ correlationId
1647
+ );
1648
+ }
1649
+
1650
+ /**
1651
+ * Returns new instance of the Silent Refresh Interaction Client
1652
+ */
1653
+ protected createSilentRefreshClient(
1654
+ correlationId?: string
1655
+ ): SilentRefreshClient {
1656
+ return new SilentRefreshClient(
1657
+ this.config,
1658
+ this.browserStorage,
1659
+ this.browserCrypto,
1660
+ this.logger,
1661
+ this.eventHandler,
1662
+ this.navigationClient,
1663
+ this.performanceClient,
1664
+ this.nativeExtensionProvider,
1665
+ correlationId
1666
+ );
1667
+ }
1668
+
1669
+ /**
1670
+ * Returns new instance of the Silent AuthCode Interaction Client
1671
+ */
1672
+ protected createSilentAuthCodeClient(
1673
+ correlationId?: string
1674
+ ): SilentAuthCodeClient {
1675
+ return new SilentAuthCodeClient(
1676
+ this.config,
1677
+ this.browserStorage,
1678
+ this.browserCrypto,
1679
+ this.logger,
1680
+ this.eventHandler,
1681
+ this.navigationClient,
1682
+ ApiId.acquireTokenByCode,
1683
+ this.performanceClient,
1684
+ this.nativeExtensionProvider,
1685
+ correlationId
1686
+ );
1687
+ }
1688
+
1689
+ /**
1690
+ * Adds event callbacks to array
1691
+ * @param callback
1692
+ */
1693
+ addEventCallback(callback: EventCallbackFunction): string | null {
1694
+ return this.eventHandler.addEventCallback(callback);
1695
+ }
1696
+
1697
+ /**
1698
+ * Removes callback with provided id from callback array
1699
+ * @param callbackId
1700
+ */
1701
+ removeEventCallback(callbackId: string): void {
1702
+ this.eventHandler.removeEventCallback(callbackId);
1703
+ }
1704
+
1705
+ /**
1706
+ * Registers a callback to receive performance events.
1707
+ *
1708
+ * @param {PerformanceCallbackFunction} callback
1709
+ * @returns {string}
1710
+ */
1711
+ addPerformanceCallback(callback: PerformanceCallbackFunction): string {
1712
+ return this.performanceClient.addPerformanceCallback(callback);
1713
+ }
1714
+
1715
+ /**
1716
+ * Removes a callback registered with addPerformanceCallback.
1717
+ *
1718
+ * @param {string} callbackId
1719
+ * @returns {boolean}
1720
+ */
1721
+ removePerformanceCallback(callbackId: string): boolean {
1722
+ return this.performanceClient.removePerformanceCallback(callbackId);
1723
+ }
1724
+
1725
+ /**
1726
+ * Adds event listener that emits an event when a user account is added or removed from localstorage in a different browser tab or window
1727
+ */
1728
+ enableAccountStorageEvents(): void {
1729
+ this.eventHandler.enableAccountStorageEvents();
1730
+ }
1731
+
1732
+ /**
1733
+ * Removes event listener that emits an event when a user account is added or removed from localstorage in a different browser tab or window
1734
+ */
1735
+ disableAccountStorageEvents(): void {
1736
+ this.eventHandler.disableAccountStorageEvents();
1737
+ }
1738
+
1739
+ /**
1740
+ * Gets the token cache for the application.
1741
+ */
1742
+ getTokenCache(): ITokenCache {
1743
+ return this.tokenCache;
1744
+ }
1745
+
1746
+ /**
1747
+ * Returns the logger instance
1748
+ */
1749
+ public getLogger(): Logger {
1750
+ return this.logger;
1751
+ }
1752
+
1753
+ /**
1754
+ * Replaces the default logger set in configurations with new Logger with new configurations
1755
+ * @param logger Logger instance
1756
+ */
1757
+ setLogger(logger: Logger): void {
1758
+ this.logger = logger;
1759
+ }
1760
+
1761
+ /**
1762
+ * Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
1763
+ * @param sku
1764
+ * @param version
1765
+ */
1766
+ initializeWrapperLibrary(sku: WrapperSKU, version: string): void {
1767
+ // Validate the SKU passed in is one we expect
1768
+ this.browserStorage.setWrapperMetadata(sku, version);
1769
+ }
1770
+
1771
+ /**
1772
+ * Sets navigation client
1773
+ * @param navigationClient
1774
+ */
1775
+ setNavigationClient(navigationClient: INavigationClient): void {
1776
+ this.navigationClient = navigationClient;
1777
+ }
1778
+
1779
+ /**
1780
+ * Returns the configuration object
1781
+ */
1782
+ public getConfiguration(): BrowserConfiguration {
1783
+ return this.config;
1784
+ }
1785
+
1786
+ /**
1787
+ * Returns the performance client
1788
+ */
1789
+ public getPerformanceClient(): IPerformanceClient {
1790
+ return this.performanceClient;
1791
+ }
1792
+
1793
+ /**
1794
+ * Returns the browser storage
1795
+ */
1796
+ public getBrowserStorage(): BrowserCacheManager {
1797
+ return this.browserStorage;
1798
+ }
1799
+
1800
+ /**
1801
+ * Returns the browser env indicator
1802
+ */
1803
+ public isBrowserEnv(): boolean {
1804
+ return this.isBrowserEnvironment;
1805
+ }
1806
+
1807
+ /**
1808
+ * Returns the event handler
1809
+ */
1810
+ getEventHandler(): EventHandler {
1811
+ return this.eventHandler;
1812
+ }
1813
+
1814
+ /**
1815
+ * Generates a correlation id for a request if none is provided.
1816
+ *
1817
+ * @protected
1818
+ * @param {?Partial<BaseAuthRequest>} [request]
1819
+ * @returns {string}
1820
+ */
1821
+ protected getRequestCorrelationId(
1822
+ request?: Partial<BaseAuthRequest>
1823
+ ): string {
1824
+ if (request?.correlationId) {
1825
+ return request.correlationId;
1826
+ }
1827
+
1828
+ if (this.isBrowserEnvironment) {
1829
+ return createNewGuid();
1830
+ }
1831
+
1832
+ /*
1833
+ * Included for fallback for non-browser environments,
1834
+ * and to ensure this method always returns a string.
1835
+ */
1836
+ return Constants.EMPTY_STRING;
1837
+ }
1838
+
1839
+ // #endregion
1840
+
1841
+ /**
1842
+ * Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
1843
+ * any code that follows this function will not execute.
1844
+ *
1845
+ * 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
1846
+ * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
1847
+ *
1848
+ * @param request
1849
+ */
1850
+ async loginRedirect(request?: RedirectRequest): Promise<void> {
1851
+ const correlationId: string = this.getRequestCorrelationId(request);
1852
+ this.logger.verbose("loginRedirect called", correlationId);
1853
+ return this.acquireTokenRedirect({
1854
+ correlationId,
1855
+ ...(request || DEFAULT_REQUEST),
1856
+ });
1857
+ }
1858
+
1859
+ /**
1860
+ * Use when initiating the login process via opening a popup window in the user's browser
1861
+ *
1862
+ * @param request
1863
+ *
1864
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
1865
+ */
1866
+ loginPopup(request?: PopupRequest): Promise<AuthenticationResult> {
1867
+ const correlationId: string = this.getRequestCorrelationId(request);
1868
+ this.logger.verbose("loginPopup called", correlationId);
1869
+ return this.acquireTokenPopup({
1870
+ correlationId,
1871
+ ...(request || DEFAULT_REQUEST),
1872
+ });
1873
+ }
1874
+
1875
+ /**
1876
+ * Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
1877
+ *
1878
+ * @param {@link (SilentRequest:type)}
1879
+ * @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
1880
+ */
1881
+ async acquireTokenSilent(
1882
+ request: SilentRequest
1883
+ ): Promise<AuthenticationResult> {
1884
+ const correlationId = this.getRequestCorrelationId(request);
1885
+ const atsMeasurement = this.performanceClient.startMeasurement(
1886
+ PerformanceEvents.AcquireTokenSilent,
1887
+ correlationId
1888
+ );
1889
+ atsMeasurement.add({
1890
+ cacheLookupPolicy: request.cacheLookupPolicy,
1891
+ });
1892
+
1893
+ this.preflightBrowserEnvironmentCheck(InteractionType.Silent);
1894
+ this.logger.verbose("acquireTokenSilent called", correlationId);
1895
+
1896
+ const account = request.account || this.getActiveAccount();
1897
+ if (!account) {
1898
+ throw createBrowserAuthError(BrowserAuthErrorCodes.noAccountError);
1899
+ }
1900
+
1901
+ const thumbprint: RequestThumbprint = {
1902
+ clientId: this.config.auth.clientId,
1903
+ authority: request.authority || Constants.EMPTY_STRING,
1904
+ scopes: request.scopes,
1905
+ homeAccountIdentifier: account.homeAccountId,
1906
+ claims: request.claims,
1907
+ authenticationScheme: request.authenticationScheme,
1908
+ resourceRequestMethod: request.resourceRequestMethod,
1909
+ resourceRequestUri: request.resourceRequestUri,
1910
+ shrClaims: request.shrClaims,
1911
+ sshKid: request.sshKid,
1912
+ };
1913
+ const silentRequestKey = JSON.stringify(thumbprint);
1914
+
1915
+ const cachedResponse =
1916
+ this.activeSilentTokenRequests.get(silentRequestKey);
1917
+ if (typeof cachedResponse === "undefined") {
1918
+ this.logger.verbose(
1919
+ "acquireTokenSilent called for the first time, storing active request",
1920
+ correlationId
1921
+ );
1922
+
1923
+ const response = invokeAsync(
1924
+ this.acquireTokenSilentAsync.bind(this),
1925
+ PerformanceEvents.AcquireTokenSilentAsync,
1926
+ this.logger,
1927
+ this.performanceClient,
1928
+ correlationId
1929
+ )(
1930
+ {
1931
+ ...request,
1932
+ correlationId,
1933
+ },
1934
+ account
1935
+ )
1936
+ .then((result) => {
1937
+ this.activeSilentTokenRequests.delete(silentRequestKey);
1938
+ atsMeasurement.add({
1939
+ accessTokenSize: result.accessToken.length,
1940
+ idTokenSize: result.idToken.length,
1941
+ });
1942
+ atsMeasurement.end({
1943
+ success: true,
1944
+ fromCache: result.fromCache,
1945
+ isNativeBroker: result.fromNativeBroker,
1946
+ cacheLookupPolicy: request.cacheLookupPolicy,
1947
+ requestId: result.requestId,
1948
+ });
1949
+ return result;
1950
+ })
1951
+ .catch((error: AuthError) => {
1952
+ this.activeSilentTokenRequests.delete(silentRequestKey);
1953
+ atsMeasurement.end({
1954
+ errorCode: error.errorCode,
1955
+ subErrorCode: error.subError,
1956
+ success: false,
1957
+ });
1958
+ throw error;
1959
+ });
1960
+ this.activeSilentTokenRequests.set(silentRequestKey, response);
1961
+ return response;
1962
+ } else {
1963
+ this.logger.verbose(
1964
+ "acquireTokenSilent has been called previously, returning the result from the first call",
1965
+ correlationId
1966
+ );
1967
+ // Discard measurements for memoized calls, as they are usually only a couple of ms and will artificially deflate metrics
1968
+ atsMeasurement.discard();
1969
+ return cachedResponse;
1970
+ }
1971
+ }
1972
+
1973
+ /**
1974
+ * 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.
1975
+ * @param {@link (SilentRequest:type)}
1976
+ * @param {@link (AccountInfo:type)}
1977
+ * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse}
1978
+ */
1979
+ protected async acquireTokenSilentAsync(
1980
+ request: SilentRequest,
1981
+ account: AccountInfo
1982
+ ): Promise<AuthenticationResult> {
1983
+ this.performanceClient.addQueueMeasurement(
1984
+ PerformanceEvents.AcquireTokenSilentAsync,
1985
+ request.correlationId
1986
+ );
1987
+
1988
+ this.eventHandler.emitEvent(
1989
+ EventType.ACQUIRE_TOKEN_START,
1990
+ InteractionType.Silent,
1991
+ request
1992
+ );
1993
+ this.atsAsyncMeasurement = this.performanceClient.startMeasurement(
1994
+ PerformanceEvents.AcquireTokenSilentAsync,
1995
+ request.correlationId
1996
+ );
1997
+ this.atsAsyncMeasurement?.increment({
1998
+ visibilityChangeCount: 0,
1999
+ });
2000
+ document.addEventListener("visibilitychange", this.trackPageVisibility);
2001
+ let result: Promise<AuthenticationResult>;
2002
+ if (
2003
+ NativeMessageHandler.isNativeAvailable(
2004
+ this.config,
2005
+ this.logger,
2006
+ this.nativeExtensionProvider,
2007
+ request.authenticationScheme
2008
+ ) &&
2009
+ account.nativeAccountId
2010
+ ) {
2011
+ this.logger.verbose(
2012
+ "acquireTokenSilent - attempting to acquire token from native platform"
2013
+ );
2014
+ const silentRequest: SilentRequest = {
2015
+ ...request,
2016
+ account,
2017
+ };
2018
+ result = this.acquireTokenNative(
2019
+ silentRequest,
2020
+ ApiId.acquireTokenSilent_silentFlow
2021
+ ).catch(async (e: AuthError) => {
2022
+ // If native token acquisition fails for availability reasons fallback to web flow
2023
+ if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
2024
+ this.logger.verbose(
2025
+ "acquireTokenSilent - native platform unavailable, falling back to web flow"
2026
+ );
2027
+ this.nativeExtensionProvider = undefined; // Prevent future requests from continuing to attempt
2028
+
2029
+ // Cache will not contain tokens, given that previous WAM requests succeeded. Skip cache and RT renewal and go straight to iframe renewal
2030
+ const silentIframeClient = this.createSilentIframeClient(
2031
+ request.correlationId
2032
+ );
2033
+ return silentIframeClient.acquireToken(request);
2034
+ }
2035
+ throw e;
2036
+ });
2037
+ } else {
2038
+ this.logger.verbose(
2039
+ "acquireTokenSilent - attempting to acquire token from web flow"
2040
+ );
2041
+
2042
+ const silentCacheClient = this.createSilentCacheClient(
2043
+ request.correlationId
2044
+ );
2045
+
2046
+ const silentRequest = await invokeAsync(
2047
+ silentCacheClient.initializeSilentRequest.bind(
2048
+ silentCacheClient
2049
+ ),
2050
+ PerformanceEvents.InitializeSilentRequest,
2051
+ this.logger,
2052
+ this.performanceClient,
2053
+ request.correlationId
2054
+ )(request, account);
2055
+
2056
+ const requestWithCLP = {
2057
+ ...request,
2058
+ // set the request's CacheLookupPolicy to Default if it was not optionally passed in
2059
+ cacheLookupPolicy:
2060
+ request.cacheLookupPolicy || CacheLookupPolicy.Default,
2061
+ };
2062
+
2063
+ result = invokeAsync(
2064
+ this.acquireTokenFromCache.bind(this),
2065
+ PerformanceEvents.AcquireTokenFromCache,
2066
+ this.logger,
2067
+ this.performanceClient,
2068
+ silentRequest.correlationId
2069
+ )(silentCacheClient, silentRequest, requestWithCLP).catch(
2070
+ (cacheError: AuthError) => {
2071
+ if (
2072
+ requestWithCLP.cacheLookupPolicy ===
2073
+ CacheLookupPolicy.AccessToken
2074
+ ) {
2075
+ throw cacheError;
2076
+ }
2077
+
2078
+ // block the reload if it occurred inside a hidden iframe
2079
+ BrowserUtils.blockReloadInHiddenIframes();
2080
+ this.eventHandler.emitEvent(
2081
+ EventType.ACQUIRE_TOKEN_NETWORK_START,
2082
+ InteractionType.Silent,
2083
+ silentRequest
2084
+ );
2085
+
2086
+ return invokeAsync(
2087
+ this.acquireTokenByRefreshToken.bind(this),
2088
+ PerformanceEvents.AcquireTokenByRefreshToken,
2089
+ this.logger,
2090
+ this.performanceClient,
2091
+ silentRequest.correlationId
2092
+ )(silentRequest, requestWithCLP).catch(
2093
+ (refreshTokenError: AuthError) => {
2094
+ const isServerError =
2095
+ refreshTokenError instanceof ServerError;
2096
+ const isInteractionRequiredError =
2097
+ refreshTokenError instanceof
2098
+ InteractionRequiredAuthError;
2099
+ const isInvalidGrantError =
2100
+ refreshTokenError.errorCode ===
2101
+ BrowserConstants.INVALID_GRANT_ERROR;
2102
+
2103
+ if (
2104
+ (!isServerError ||
2105
+ !isInvalidGrantError ||
2106
+ isInteractionRequiredError ||
2107
+ requestWithCLP.cacheLookupPolicy ===
2108
+ CacheLookupPolicy.AccessTokenAndRefreshToken ||
2109
+ requestWithCLP.cacheLookupPolicy ===
2110
+ CacheLookupPolicy.RefreshToken) &&
2111
+ requestWithCLP.cacheLookupPolicy !==
2112
+ CacheLookupPolicy.Skip
2113
+ ) {
2114
+ throw refreshTokenError;
2115
+ }
2116
+
2117
+ this.logger.verbose(
2118
+ "Refresh token expired/invalid or CacheLookupPolicy is set to Skip, attempting acquire token by iframe.",
2119
+ request.correlationId
2120
+ );
2121
+ return invokeAsync(
2122
+ this.acquireTokenBySilentIframe.bind(this),
2123
+ PerformanceEvents.AcquireTokenBySilentIframe,
2124
+ this.logger,
2125
+ this.performanceClient,
2126
+ silentRequest.correlationId
2127
+ )(silentRequest);
2128
+ }
2129
+ );
2130
+ }
2131
+ );
2132
+ }
2133
+
2134
+ return result
2135
+ .then((response) => {
2136
+ this.eventHandler.emitEvent(
2137
+ EventType.ACQUIRE_TOKEN_SUCCESS,
2138
+ InteractionType.Silent,
2139
+ response
2140
+ );
2141
+ this.atsAsyncMeasurement?.end({
2142
+ success: true,
2143
+ fromCache: response.fromCache,
2144
+ isNativeBroker: response.fromNativeBroker,
2145
+ requestId: response.requestId,
2146
+ });
2147
+ return response;
2148
+ })
2149
+ .catch((tokenRenewalError: AuthError) => {
2150
+ this.eventHandler.emitEvent(
2151
+ EventType.ACQUIRE_TOKEN_FAILURE,
2152
+ InteractionType.Silent,
2153
+ null,
2154
+ tokenRenewalError
2155
+ );
2156
+ this.atsAsyncMeasurement?.end({
2157
+ errorCode: tokenRenewalError.errorCode,
2158
+ subErrorCode: tokenRenewalError.subError,
2159
+ success: false,
2160
+ });
2161
+ throw tokenRenewalError;
2162
+ })
2163
+ .finally(() => {
2164
+ document.removeEventListener(
2165
+ "visibilitychange",
2166
+ this.trackPageVisibility
2167
+ );
2168
+ });
2169
+ }
2170
+ }