@azure/msal-browser 3.20.0 → 3.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/app/IPublicClientApplication.d.ts +53 -53
  2. package/dist/app/IPublicClientApplication.mjs +105 -105
  3. package/dist/app/PublicClientApplication.d.ts +293 -293
  4. package/dist/app/PublicClientApplication.mjs +364 -364
  5. package/dist/app/PublicClientNext.d.ts +276 -276
  6. package/dist/app/PublicClientNext.mjs +354 -354
  7. package/dist/broker/nativeBroker/NativeMessageHandler.d.ts +62 -62
  8. package/dist/broker/nativeBroker/NativeMessageHandler.mjs +254 -254
  9. package/dist/broker/nativeBroker/NativeRequest.d.ts +45 -45
  10. package/dist/broker/nativeBroker/NativeResponse.d.ts +48 -48
  11. package/dist/broker/nativeBroker/NativeStatusCodes.d.ts +7 -7
  12. package/dist/broker/nativeBroker/NativeStatusCodes.mjs +11 -11
  13. package/dist/cache/AccountManager.d.ts +48 -48
  14. package/dist/cache/AccountManager.mjs +126 -126
  15. package/dist/cache/AsyncMemoryStorage.d.ts +50 -50
  16. package/dist/cache/AsyncMemoryStorage.mjs +131 -131
  17. package/dist/cache/BrowserCacheManager.d.ts +385 -385
  18. package/dist/cache/BrowserCacheManager.mjs +1294 -1294
  19. package/dist/cache/BrowserStorage.d.ts +11 -11
  20. package/dist/cache/BrowserStorage.mjs +32 -32
  21. package/dist/cache/DatabaseStorage.d.ts +56 -56
  22. package/dist/cache/DatabaseStorage.mjs +200 -200
  23. package/dist/cache/IAsyncStorage.d.ts +27 -27
  24. package/dist/cache/ITokenCache.d.ts +11 -11
  25. package/dist/cache/IWindowStorage.d.ts +27 -27
  26. package/dist/cache/MemoryStorage.d.ts +11 -11
  27. package/dist/cache/MemoryStorage.mjs +31 -31
  28. package/dist/cache/TokenCache.d.ts +77 -77
  29. package/dist/cache/TokenCache.mjs +195 -195
  30. package/dist/config/Configuration.d.ts +213 -208
  31. package/dist/config/Configuration.d.ts.map +1 -1
  32. package/dist/config/Configuration.mjs +128 -128
  33. package/dist/config/Configuration.mjs.map +1 -1
  34. package/dist/controllers/ControllerFactory.d.ts +5 -5
  35. package/dist/controllers/ControllerFactory.mjs +25 -25
  36. package/dist/controllers/IController.d.ts +60 -60
  37. package/dist/controllers/NestedAppAuthController.d.ts +202 -202
  38. package/dist/controllers/NestedAppAuthController.mjs +473 -473
  39. package/dist/controllers/StandardController.d.ts +405 -405
  40. package/dist/controllers/StandardController.d.ts.map +1 -1
  41. package/dist/controllers/StandardController.mjs +1334 -1316
  42. package/dist/controllers/StandardController.mjs.map +1 -1
  43. package/dist/controllers/UnknownOperatingContextController.d.ts +86 -86
  44. package/dist/controllers/UnknownOperatingContextController.mjs +256 -256
  45. package/dist/crypto/BrowserCrypto.d.ts +52 -52
  46. package/dist/crypto/BrowserCrypto.mjs +151 -151
  47. package/dist/crypto/CryptoOps.d.ts +74 -74
  48. package/dist/crypto/CryptoOps.mjs +176 -176
  49. package/dist/crypto/PkceGenerator.d.ts +8 -8
  50. package/dist/crypto/PkceGenerator.mjs +54 -54
  51. package/dist/crypto/SignedHttpRequest.d.ts +30 -30
  52. package/dist/crypto/SignedHttpRequest.mjs +39 -39
  53. package/dist/encode/Base64Decode.d.ts +9 -9
  54. package/dist/encode/Base64Decode.mjs +36 -36
  55. package/dist/encode/Base64Encode.d.ts +19 -19
  56. package/dist/encode/Base64Encode.mjs +43 -43
  57. package/dist/error/BrowserAuthError.d.ts +255 -255
  58. package/dist/error/BrowserAuthError.mjs +263 -263
  59. package/dist/error/BrowserAuthErrorCodes.d.ts +46 -46
  60. package/dist/error/BrowserAuthErrorCodes.mjs +50 -50
  61. package/dist/error/BrowserConfigurationAuthError.d.ts +33 -33
  62. package/dist/error/BrowserConfigurationAuthError.mjs +40 -40
  63. package/dist/error/BrowserConfigurationAuthError.mjs.map +1 -1
  64. package/dist/error/BrowserConfigurationAuthErrorCodes.d.ts +3 -3
  65. package/dist/error/BrowserConfigurationAuthErrorCodes.mjs +7 -7
  66. package/dist/error/NativeAuthError.d.ts +29 -29
  67. package/dist/error/NativeAuthError.mjs +60 -60
  68. package/dist/error/NativeAuthErrorCodes.d.ts +2 -2
  69. package/dist/error/NativeAuthErrorCodes.mjs +6 -6
  70. package/dist/error/NestedAppAuthError.d.ts +14 -14
  71. package/dist/error/NestedAppAuthError.mjs +23 -23
  72. package/dist/event/EventHandler.d.ts +41 -41
  73. package/dist/event/EventHandler.mjs +125 -125
  74. package/dist/event/EventMessage.d.ts +25 -25
  75. package/dist/event/EventMessage.mjs +68 -68
  76. package/dist/event/EventType.d.ts +29 -29
  77. package/dist/event/EventType.mjs +32 -32
  78. package/dist/index.d.ts +40 -40
  79. package/dist/index.mjs +1 -1
  80. package/dist/interaction_client/BaseInteractionClient.d.ts +50 -50
  81. package/dist/interaction_client/BaseInteractionClient.mjs +106 -106
  82. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.d.ts +4 -4
  83. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.mjs +10 -10
  84. package/dist/interaction_client/NativeInteractionClient.d.ts +151 -151
  85. package/dist/interaction_client/NativeInteractionClient.mjs +621 -621
  86. package/dist/interaction_client/PopupClient.d.ts +105 -105
  87. package/dist/interaction_client/PopupClient.d.ts.map +1 -1
  88. package/dist/interaction_client/PopupClient.mjs +433 -433
  89. package/dist/interaction_client/PopupClient.mjs.map +1 -1
  90. package/dist/interaction_client/RedirectClient.d.ts +50 -50
  91. package/dist/interaction_client/RedirectClient.d.ts.map +1 -1
  92. package/dist/interaction_client/RedirectClient.mjs +315 -314
  93. package/dist/interaction_client/RedirectClient.mjs.map +1 -1
  94. package/dist/interaction_client/SilentAuthCodeClient.d.ts +23 -23
  95. package/dist/interaction_client/SilentAuthCodeClient.mjs +57 -57
  96. package/dist/interaction_client/SilentCacheClient.d.ts +16 -16
  97. package/dist/interaction_client/SilentCacheClient.mjs +42 -42
  98. package/dist/interaction_client/SilentIframeClient.d.ts +32 -32
  99. package/dist/interaction_client/SilentIframeClient.d.ts.map +1 -1
  100. package/dist/interaction_client/SilentIframeClient.mjs +110 -100
  101. package/dist/interaction_client/SilentIframeClient.mjs.map +1 -1
  102. package/dist/interaction_client/SilentRefreshClient.d.ts +20 -20
  103. package/dist/interaction_client/SilentRefreshClient.mjs +47 -47
  104. package/dist/interaction_client/StandardInteractionClient.d.ts +48 -48
  105. package/dist/interaction_client/StandardInteractionClient.mjs +199 -199
  106. package/dist/interaction_handler/InteractionHandler.d.ts +33 -33
  107. package/dist/interaction_handler/InteractionHandler.mjs +93 -93
  108. package/dist/interaction_handler/RedirectHandler.d.ts +32 -32
  109. package/dist/interaction_handler/RedirectHandler.mjs +134 -134
  110. package/dist/interaction_handler/SilentHandler.d.ts +13 -13
  111. package/dist/interaction_handler/SilentHandler.mjs +134 -134
  112. package/dist/naa/AccountInfo.d.ts +11 -11
  113. package/dist/naa/AuthBridge.d.ts +8 -8
  114. package/dist/naa/AuthResult.d.ts +6 -6
  115. package/dist/naa/BridgeAccountContext.d.ts +12 -12
  116. package/dist/naa/BridgeCapabilities.d.ts +3 -3
  117. package/dist/naa/BridgeError.d.ts +9 -9
  118. package/dist/naa/BridgeError.mjs +7 -7
  119. package/dist/naa/BridgeProxy.d.ts +67 -67
  120. package/dist/naa/BridgeProxy.mjs +148 -148
  121. package/dist/naa/BridgeRequest.d.ts +7 -7
  122. package/dist/naa/BridgeRequestEnvelope.d.ts +12 -12
  123. package/dist/naa/BridgeResponseEnvelope.d.ts +13 -13
  124. package/dist/naa/BridgeStatusCode.d.ts +11 -11
  125. package/dist/naa/BridgeStatusCode.mjs +14 -14
  126. package/dist/naa/IBridgeProxy.d.ts +10 -10
  127. package/dist/naa/InitContext.d.ts +8 -8
  128. package/dist/naa/TokenRequest.d.ts +18 -18
  129. package/dist/naa/TokenResponse.d.ts +13 -13
  130. package/dist/naa/mapping/NestedAppAuthAdapter.d.ts +35 -35
  131. package/dist/naa/mapping/NestedAppAuthAdapter.mjs +179 -179
  132. package/dist/navigation/INavigationClient.d.ts +16 -16
  133. package/dist/navigation/NavigationClient.d.ts +22 -22
  134. package/dist/navigation/NavigationClient.mjs +40 -40
  135. package/dist/navigation/NavigationOptions.d.ts +12 -12
  136. package/dist/network/FetchClient.d.ts +26 -26
  137. package/dist/network/FetchClient.mjs +99 -99
  138. package/dist/operatingcontext/BaseOperatingContext.d.ts +41 -41
  139. package/dist/operatingcontext/BaseOperatingContext.mjs +94 -94
  140. package/dist/operatingcontext/NestedAppOperatingContext.d.ts +34 -34
  141. package/dist/operatingcontext/NestedAppOperatingContext.mjs +71 -71
  142. package/dist/operatingcontext/StandardOperatingContext.d.ts +25 -25
  143. package/dist/operatingcontext/StandardOperatingContext.mjs +43 -43
  144. package/dist/operatingcontext/UnknownOperatingContext.d.ts +25 -25
  145. package/dist/operatingcontext/UnknownOperatingContext.mjs +42 -42
  146. package/dist/packageMetadata.d.ts +2 -2
  147. package/dist/packageMetadata.mjs +4 -4
  148. package/dist/request/AuthorizationCodeRequest.d.ts +8 -8
  149. package/dist/request/AuthorizationUrlRequest.d.ts +8 -8
  150. package/dist/request/ClearCacheRequest.d.ts +10 -10
  151. package/dist/request/EndSessionPopupRequest.d.ts +18 -18
  152. package/dist/request/EndSessionRequest.d.ts +15 -15
  153. package/dist/request/InitializeApplicationRequest.d.ts +8 -8
  154. package/dist/request/PopupRequest.d.ts +34 -34
  155. package/dist/request/PopupWindowAttributes.d.ts +15 -15
  156. package/dist/request/RedirectRequest.d.ts +40 -35
  157. package/dist/request/RedirectRequest.d.ts.map +1 -1
  158. package/dist/request/RequestHelpers.d.ts +13 -13
  159. package/dist/request/RequestHelpers.mjs +53 -53
  160. package/dist/request/SilentRequest.d.ts +33 -33
  161. package/dist/request/SsoSilentRequest.d.ts +29 -29
  162. package/dist/response/AuthenticationResult.d.ts +4 -4
  163. package/dist/response/ResponseHandler.d.ts +7 -7
  164. package/dist/response/ResponseHandler.mjs +36 -36
  165. package/dist/telemetry/BrowserPerformanceClient.d.ts +34 -34
  166. package/dist/telemetry/BrowserPerformanceClient.mjs +162 -162
  167. package/dist/telemetry/BrowserPerformanceMeasurement.d.ts +21 -21
  168. package/dist/telemetry/BrowserPerformanceMeasurement.mjs +92 -92
  169. package/dist/utils/BrowserConstants.d.ts +180 -180
  170. package/dist/utils/BrowserConstants.mjs +212 -212
  171. package/dist/utils/BrowserProtocolUtils.d.ts +11 -11
  172. package/dist/utils/BrowserProtocolUtils.mjs +21 -21
  173. package/dist/utils/BrowserUtils.d.ts +75 -75
  174. package/dist/utils/BrowserUtils.mjs +157 -157
  175. package/lib/msal-browser.cjs +18884 -18855
  176. package/lib/msal-browser.cjs.map +1 -1
  177. package/lib/msal-browser.js +18884 -18855
  178. package/lib/msal-browser.js.map +1 -1
  179. package/lib/msal-browser.min.js +59 -59
  180. package/package.json +2 -2
  181. package/src/config/Configuration.ts +9 -1
  182. package/src/controllers/StandardController.ts +30 -12
  183. package/src/interaction_client/PopupClient.ts +1 -0
  184. package/src/interaction_client/RedirectClient.ts +4 -1
  185. package/src/interaction_client/SilentIframeClient.ts +40 -3
  186. package/src/packageMetadata.ts +1 -1
  187. package/src/request/RedirectRequest.ts +5 -0
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-browser v3.20.0 2024-07-23 */
1
+ /*! @azure/msal-browser v3.22.0 2024-08-28 */
2
2
  'use strict';
3
3
  import { invokeAsync, PerformanceEvents, AuthError, Constants, UrlString, UrlUtils, ProtocolUtils, ThrottlingUtils, ProtocolMode, ServerResponseType } from '@azure/msal-common';
4
4
  import { StandardInteractionClient } from './StandardInteractionClient.mjs';
@@ -12,319 +12,320 @@ import { NativeMessageHandler } from '../broker/nativeBroker/NativeMessageHandle
12
12
  import { validateInteractionType } from '../response/ResponseHandler.mjs';
13
13
  import { noStateInHash, nativeConnectionNotEstablished, noCachedAuthorityError } from '../error/BrowserAuthErrorCodes.mjs';
14
14
 
15
- /*
16
- * Copyright (c) Microsoft Corporation. All rights reserved.
17
- * Licensed under the MIT License.
18
- */
19
- class RedirectClient extends StandardInteractionClient {
20
- constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeStorageImpl, nativeMessageHandler, correlationId) {
21
- super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeMessageHandler, correlationId);
22
- this.nativeStorage = nativeStorageImpl;
23
- }
24
- /**
25
- * Redirects the page to the /authorize endpoint of the IDP
26
- * @param request
27
- */
28
- async acquireToken(request) {
29
- const validRequest = await invokeAsync(this.initializeAuthorizationRequest.bind(this), PerformanceEvents.StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(request, InteractionType.Redirect);
30
- this.browserStorage.updateCacheEntries(validRequest.state, validRequest.nonce, validRequest.authority, validRequest.loginHint || "", validRequest.account || null);
31
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenRedirect);
32
- const handleBackButton = (event) => {
33
- // Clear temporary cache if the back button is clicked during the redirect flow.
34
- if (event.persisted) {
35
- this.logger.verbose("Page was restored from back/forward cache. Clearing temporary cache.");
36
- this.browserStorage.cleanRequestByState(validRequest.state);
37
- this.eventHandler.emitEvent(EventType.RESTORE_FROM_BFCACHE, InteractionType.Redirect);
38
- }
39
- };
40
- try {
41
- // Create auth code request and generate PKCE params
42
- const authCodeRequest = await invokeAsync(this.initializeAuthorizationCodeRequest.bind(this), PerformanceEvents.StandardInteractionClientInitializeAuthorizationCodeRequest, this.logger, this.performanceClient, this.correlationId)(validRequest);
43
- // Initialize the client
44
- const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)(serverTelemetryManager, validRequest.authority, validRequest.azureCloudOptions, validRequest.account);
45
- // Create redirect interaction handler.
46
- const interactionHandler = new RedirectHandler(authClient, this.browserStorage, authCodeRequest, this.logger, this.performanceClient);
47
- // Create acquire token url.
48
- const navigateUrl = await authClient.getAuthCodeUrl({
49
- ...validRequest,
50
- nativeBroker: NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeMessageHandler, request.authenticationScheme),
51
- });
52
- const redirectStartPage = this.getRedirectStartPage(request.redirectStartPage);
53
- this.logger.verbosePii(`Redirect start page: ${redirectStartPage}`);
54
- // Clear temporary cache if the back button is clicked during the redirect flow.
55
- window.addEventListener("pageshow", handleBackButton);
56
- // Show the UI once the url has been created. Response will come back in the hash, which will be handled in the handleRedirectCallback function.
57
- return await interactionHandler.initiateAuthRequest(navigateUrl, {
58
- navigationClient: this.navigationClient,
59
- redirectTimeout: this.config.system.redirectNavigationTimeout,
60
- redirectStartPage: redirectStartPage,
61
- onRedirectNavigate: request.onRedirectNavigate,
62
- });
63
- }
64
- catch (e) {
65
- if (e instanceof AuthError) {
66
- e.setCorrelationId(this.correlationId);
67
- serverTelemetryManager.cacheFailedRequest(e);
68
- }
69
- window.removeEventListener("pageshow", handleBackButton);
70
- this.browserStorage.cleanRequestByState(validRequest.state);
71
- throw e;
72
- }
73
- }
74
- /**
75
- * Checks if navigateToLoginRequestUrl is set, and:
76
- * - if true, performs logic to cache and navigate
77
- * - if false, handles hash string and parses response
78
- * @param hash {string} url hash
79
- * @param parentMeasurement {InProgressPerformanceEvent} parent measurement
80
- */
81
- async handleRedirectPromise(hash = "", parentMeasurement) {
82
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.handleRedirectPromise);
83
- try {
84
- if (!this.browserStorage.isInteractionInProgress(true)) {
85
- this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null.");
86
- return null;
87
- }
88
- const [serverParams, responseString] = this.getRedirectResponse(hash || "");
89
- if (!serverParams) {
90
- // Not a recognized server response hash or hash not associated with a redirect request
91
- this.logger.info("handleRedirectPromise did not detect a response as a result of a redirect. Cleaning temporary cache.");
92
- this.browserStorage.cleanRequestByInteractionType(InteractionType.Redirect);
93
- parentMeasurement.event.errorCode = "no_server_response";
94
- return null;
95
- }
96
- // If navigateToLoginRequestUrl is true, get the url where the redirect request was initiated
97
- const loginRequestUrl = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, true) || Constants.EMPTY_STRING;
98
- const loginRequestUrlNormalized = UrlString.removeHashFromUrl(loginRequestUrl);
99
- const currentUrlNormalized = UrlString.removeHashFromUrl(window.location.href);
100
- if (loginRequestUrlNormalized === currentUrlNormalized &&
101
- this.config.auth.navigateToLoginRequestUrl) {
102
- // We are on the page we need to navigate to - handle hash
103
- this.logger.verbose("Current page is loginRequestUrl, handling response");
104
- if (loginRequestUrl.indexOf("#") > -1) {
105
- // Replace current hash with non-msal hash, if present
106
- replaceHash(loginRequestUrl);
107
- }
108
- const handleHashResult = await this.handleResponse(serverParams, serverTelemetryManager);
109
- return handleHashResult;
110
- }
111
- else if (!this.config.auth.navigateToLoginRequestUrl) {
112
- this.logger.verbose("NavigateToLoginRequestUrl set to false, handling response");
113
- return await this.handleResponse(serverParams, serverTelemetryManager);
114
- }
115
- else if (!isInIframe() ||
116
- this.config.system.allowRedirectInIframe) {
117
- /*
118
- * Returned from authority using redirect - need to perform navigation before processing response
119
- * Cache the hash to be retrieved after the next redirect
120
- */
121
- this.browserStorage.setTemporaryCache(TemporaryCacheKeys.URL_HASH, responseString, true);
122
- const navigationOptions = {
123
- apiId: ApiId.handleRedirectPromise,
124
- timeout: this.config.system.redirectNavigationTimeout,
125
- noHistory: true,
126
- };
127
- /**
128
- * Default behavior is to redirect to the start page and not process the hash now.
129
- * The start page is expected to also call handleRedirectPromise which will process the hash in one of the checks above.
130
- */
131
- let processHashOnRedirect = true;
132
- if (!loginRequestUrl || loginRequestUrl === "null") {
133
- // Redirect to home page if login request url is null (real null or the string null)
134
- const homepage = getHomepage();
135
- // Cache the homepage under ORIGIN_URI to ensure cached hash is processed on homepage
136
- this.browserStorage.setTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, homepage, true);
137
- this.logger.warning("Unable to get valid login request url from cache, redirecting to home page");
138
- processHashOnRedirect =
139
- await this.navigationClient.navigateInternal(homepage, navigationOptions);
140
- }
141
- else {
142
- // Navigate to page that initiated the redirect request
143
- this.logger.verbose(`Navigating to loginRequestUrl: ${loginRequestUrl}`);
144
- processHashOnRedirect =
145
- await this.navigationClient.navigateInternal(loginRequestUrl, navigationOptions);
146
- }
147
- // If navigateInternal implementation returns false, handle the hash now
148
- if (!processHashOnRedirect) {
149
- return await this.handleResponse(serverParams, serverTelemetryManager);
150
- }
151
- }
152
- return null;
153
- }
154
- catch (e) {
155
- if (e instanceof AuthError) {
156
- e.setCorrelationId(this.correlationId);
157
- serverTelemetryManager.cacheFailedRequest(e);
158
- }
159
- this.browserStorage.cleanRequestByInteractionType(InteractionType.Redirect);
160
- throw e;
161
- }
162
- }
163
- /**
164
- * Gets the response hash for a redirect request
165
- * Returns null if interactionType in the state value is not "redirect" or the hash does not contain known properties
166
- * @param hash
167
- */
168
- getRedirectResponse(userProvidedResponse) {
169
- this.logger.verbose("getRedirectResponseHash called");
170
- // Get current location hash from window or cache.
171
- let responseString = userProvidedResponse;
172
- if (!responseString) {
173
- if (this.config.auth.OIDCOptions.serverResponseType ===
174
- ServerResponseType.QUERY) {
175
- responseString = window.location.search;
176
- }
177
- else {
178
- responseString = window.location.hash;
179
- }
180
- }
181
- let response = UrlUtils.getDeserializedResponse(responseString);
182
- if (response) {
183
- try {
184
- validateInteractionType(response, this.browserCrypto, InteractionType.Redirect);
185
- }
186
- catch (e) {
187
- if (e instanceof AuthError) {
188
- this.logger.error(`Interaction type validation failed due to ${e.errorCode}: ${e.errorMessage}`);
189
- }
190
- return [null, ""];
191
- }
192
- clearHash(window);
193
- this.logger.verbose("Hash contains known properties, returning response hash");
194
- return [response, responseString];
195
- }
196
- const cachedHash = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.URL_HASH, true);
197
- this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.URL_HASH));
198
- if (cachedHash) {
199
- response = UrlUtils.getDeserializedResponse(cachedHash);
200
- if (response) {
201
- this.logger.verbose("Hash does not contain known properties, returning cached hash");
202
- return [response, cachedHash];
203
- }
204
- }
205
- return [null, ""];
206
- }
207
- /**
208
- * Checks if hash exists and handles in window.
209
- * @param hash
210
- * @param state
211
- */
212
- async handleResponse(serverParams, serverTelemetryManager) {
213
- const state = serverParams.state;
214
- if (!state) {
215
- throw createBrowserAuthError(noStateInHash);
216
- }
217
- const cachedRequest = this.browserStorage.getCachedRequest(state);
218
- this.logger.verbose("handleResponse called, retrieved cached request");
219
- if (serverParams.accountId) {
220
- this.logger.verbose("Account id found in hash, calling WAM for token");
221
- if (!this.nativeMessageHandler) {
222
- throw createBrowserAuthError(nativeConnectionNotEstablished);
223
- }
224
- const nativeInteractionClient = new NativeInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenPopup, this.performanceClient, this.nativeMessageHandler, serverParams.accountId, this.nativeStorage, cachedRequest.correlationId);
225
- const { userRequestState } = ProtocolUtils.parseRequestState(this.browserCrypto, state);
226
- return nativeInteractionClient
227
- .acquireToken({
228
- ...cachedRequest,
229
- state: userRequestState,
230
- prompt: undefined, // Server should handle the prompt, ideally native broker can do this part silently
231
- })
232
- .finally(() => {
233
- this.browserStorage.cleanRequestByState(state);
234
- });
235
- }
236
- // Hash contains known properties - handle and return in callback
237
- const currentAuthority = this.browserStorage.getCachedAuthority(state);
238
- if (!currentAuthority) {
239
- throw createBrowserAuthError(noCachedAuthorityError);
240
- }
241
- const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)(serverTelemetryManager, currentAuthority);
242
- ThrottlingUtils.removeThrottle(this.browserStorage, this.config.auth.clientId, cachedRequest);
243
- const interactionHandler = new RedirectHandler(authClient, this.browserStorage, cachedRequest, this.logger, this.performanceClient);
244
- return interactionHandler.handleCodeResponse(serverParams, state);
245
- }
246
- /**
247
- * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
248
- * Default behaviour is to redirect the user to `window.location.href`.
249
- * @param logoutRequest
250
- */
251
- async logout(logoutRequest) {
252
- this.logger.verbose("logoutRedirect called");
253
- const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
254
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.logout);
255
- try {
256
- this.eventHandler.emitEvent(EventType.LOGOUT_START, InteractionType.Redirect, logoutRequest);
257
- // Clear cache on logout
258
- await this.clearCacheOnLogout(validLogoutRequest.account);
259
- const navigationOptions = {
260
- apiId: ApiId.logout,
261
- timeout: this.config.system.redirectNavigationTimeout,
262
- noHistory: false,
263
- };
264
- const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)(serverTelemetryManager, logoutRequest && logoutRequest.authority, undefined, // AzureCloudOptions
265
- (logoutRequest && logoutRequest.account) || undefined);
266
- if (authClient.authority.protocolMode === ProtocolMode.OIDC) {
267
- try {
268
- authClient.authority.endSessionEndpoint;
269
- }
270
- catch {
271
- if (validLogoutRequest.account?.homeAccountId) {
272
- void this.browserStorage.removeAccount(validLogoutRequest.account?.homeAccountId);
273
- this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, InteractionType.Redirect, validLogoutRequest);
274
- return;
275
- }
276
- }
277
- }
278
- // Create logout string and navigate user window to logout.
279
- const logoutUri = authClient.getLogoutUri(validLogoutRequest);
280
- this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, InteractionType.Redirect, validLogoutRequest);
281
- // Check if onRedirectNavigate is implemented, and invoke it if so
282
- if (logoutRequest &&
283
- typeof logoutRequest.onRedirectNavigate === "function") {
284
- const navigate = logoutRequest.onRedirectNavigate(logoutUri);
285
- if (navigate !== false) {
286
- this.logger.verbose("Logout onRedirectNavigate did not return false, navigating");
287
- // Ensure interaction is in progress
288
- if (!this.browserStorage.getInteractionInProgress()) {
289
- this.browserStorage.setInteractionInProgress(true);
290
- }
291
- await this.navigationClient.navigateExternal(logoutUri, navigationOptions);
292
- return;
293
- }
294
- else {
295
- // Ensure interaction is not in progress
296
- this.browserStorage.setInteractionInProgress(false);
297
- this.logger.verbose("Logout onRedirectNavigate returned false, stopping navigation");
298
- }
299
- }
300
- else {
301
- // Ensure interaction is in progress
302
- if (!this.browserStorage.getInteractionInProgress()) {
303
- this.browserStorage.setInteractionInProgress(true);
304
- }
305
- await this.navigationClient.navigateExternal(logoutUri, navigationOptions);
306
- return;
307
- }
308
- }
309
- catch (e) {
310
- if (e instanceof AuthError) {
311
- e.setCorrelationId(this.correlationId);
312
- serverTelemetryManager.cacheFailedRequest(e);
313
- }
314
- this.eventHandler.emitEvent(EventType.LOGOUT_FAILURE, InteractionType.Redirect, null, e);
315
- this.eventHandler.emitEvent(EventType.LOGOUT_END, InteractionType.Redirect);
316
- throw e;
317
- }
318
- this.eventHandler.emitEvent(EventType.LOGOUT_END, InteractionType.Redirect);
319
- }
320
- /**
321
- * Use to get the redirectStartPage either from request or use current window
322
- * @param requestStartPage
323
- */
324
- getRedirectStartPage(requestStartPage) {
325
- const redirectStartPage = requestStartPage || window.location.href;
326
- return UrlString.getAbsoluteUrl(redirectStartPage, getCurrentUri());
327
- }
15
+ /*
16
+ * Copyright (c) Microsoft Corporation. All rights reserved.
17
+ * Licensed under the MIT License.
18
+ */
19
+ class RedirectClient extends StandardInteractionClient {
20
+ constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeStorageImpl, nativeMessageHandler, correlationId) {
21
+ super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeMessageHandler, correlationId);
22
+ this.nativeStorage = nativeStorageImpl;
23
+ }
24
+ /**
25
+ * Redirects the page to the /authorize endpoint of the IDP
26
+ * @param request
27
+ */
28
+ async acquireToken(request) {
29
+ const validRequest = await invokeAsync(this.initializeAuthorizationRequest.bind(this), PerformanceEvents.StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(request, InteractionType.Redirect);
30
+ this.browserStorage.updateCacheEntries(validRequest.state, validRequest.nonce, validRequest.authority, validRequest.loginHint || "", validRequest.account || null);
31
+ const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenRedirect);
32
+ const handleBackButton = (event) => {
33
+ // Clear temporary cache if the back button is clicked during the redirect flow.
34
+ if (event.persisted) {
35
+ this.logger.verbose("Page was restored from back/forward cache. Clearing temporary cache.");
36
+ this.browserStorage.cleanRequestByState(validRequest.state);
37
+ this.eventHandler.emitEvent(EventType.RESTORE_FROM_BFCACHE, InteractionType.Redirect);
38
+ }
39
+ };
40
+ try {
41
+ // Create auth code request and generate PKCE params
42
+ const authCodeRequest = await invokeAsync(this.initializeAuthorizationCodeRequest.bind(this), PerformanceEvents.StandardInteractionClientInitializeAuthorizationCodeRequest, this.logger, this.performanceClient, this.correlationId)(validRequest);
43
+ // Initialize the client
44
+ const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)(serverTelemetryManager, validRequest.authority, validRequest.azureCloudOptions, validRequest.account);
45
+ // Create redirect interaction handler.
46
+ const interactionHandler = new RedirectHandler(authClient, this.browserStorage, authCodeRequest, this.logger, this.performanceClient);
47
+ // Create acquire token url.
48
+ const navigateUrl = await authClient.getAuthCodeUrl({
49
+ ...validRequest,
50
+ nativeBroker: NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeMessageHandler, request.authenticationScheme),
51
+ });
52
+ const redirectStartPage = this.getRedirectStartPage(request.redirectStartPage);
53
+ this.logger.verbosePii(`Redirect start page: ${redirectStartPage}`);
54
+ // Clear temporary cache if the back button is clicked during the redirect flow.
55
+ window.addEventListener("pageshow", handleBackButton);
56
+ // Show the UI once the url has been created. Response will come back in the hash, which will be handled in the handleRedirectCallback function.
57
+ return await interactionHandler.initiateAuthRequest(navigateUrl, {
58
+ navigationClient: this.navigationClient,
59
+ redirectTimeout: this.config.system.redirectNavigationTimeout,
60
+ redirectStartPage: redirectStartPage,
61
+ onRedirectNavigate: request.onRedirectNavigate ||
62
+ this.config.auth.onRedirectNavigate,
63
+ });
64
+ }
65
+ catch (e) {
66
+ if (e instanceof AuthError) {
67
+ e.setCorrelationId(this.correlationId);
68
+ serverTelemetryManager.cacheFailedRequest(e);
69
+ }
70
+ window.removeEventListener("pageshow", handleBackButton);
71
+ this.browserStorage.cleanRequestByState(validRequest.state);
72
+ throw e;
73
+ }
74
+ }
75
+ /**
76
+ * Checks if navigateToLoginRequestUrl is set, and:
77
+ * - if true, performs logic to cache and navigate
78
+ * - if false, handles hash string and parses response
79
+ * @param hash {string} url hash
80
+ * @param parentMeasurement {InProgressPerformanceEvent} parent measurement
81
+ */
82
+ async handleRedirectPromise(hash = "", parentMeasurement) {
83
+ const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.handleRedirectPromise);
84
+ try {
85
+ if (!this.browserStorage.isInteractionInProgress(true)) {
86
+ this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null.");
87
+ return null;
88
+ }
89
+ const [serverParams, responseString] = this.getRedirectResponse(hash || "");
90
+ if (!serverParams) {
91
+ // Not a recognized server response hash or hash not associated with a redirect request
92
+ this.logger.info("handleRedirectPromise did not detect a response as a result of a redirect. Cleaning temporary cache.");
93
+ this.browserStorage.cleanRequestByInteractionType(InteractionType.Redirect);
94
+ parentMeasurement.event.errorCode = "no_server_response";
95
+ return null;
96
+ }
97
+ // If navigateToLoginRequestUrl is true, get the url where the redirect request was initiated
98
+ const loginRequestUrl = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, true) || Constants.EMPTY_STRING;
99
+ const loginRequestUrlNormalized = UrlString.removeHashFromUrl(loginRequestUrl);
100
+ const currentUrlNormalized = UrlString.removeHashFromUrl(window.location.href);
101
+ if (loginRequestUrlNormalized === currentUrlNormalized &&
102
+ this.config.auth.navigateToLoginRequestUrl) {
103
+ // We are on the page we need to navigate to - handle hash
104
+ this.logger.verbose("Current page is loginRequestUrl, handling response");
105
+ if (loginRequestUrl.indexOf("#") > -1) {
106
+ // Replace current hash with non-msal hash, if present
107
+ replaceHash(loginRequestUrl);
108
+ }
109
+ const handleHashResult = await this.handleResponse(serverParams, serverTelemetryManager);
110
+ return handleHashResult;
111
+ }
112
+ else if (!this.config.auth.navigateToLoginRequestUrl) {
113
+ this.logger.verbose("NavigateToLoginRequestUrl set to false, handling response");
114
+ return await this.handleResponse(serverParams, serverTelemetryManager);
115
+ }
116
+ else if (!isInIframe() ||
117
+ this.config.system.allowRedirectInIframe) {
118
+ /*
119
+ * Returned from authority using redirect - need to perform navigation before processing response
120
+ * Cache the hash to be retrieved after the next redirect
121
+ */
122
+ this.browserStorage.setTemporaryCache(TemporaryCacheKeys.URL_HASH, responseString, true);
123
+ const navigationOptions = {
124
+ apiId: ApiId.handleRedirectPromise,
125
+ timeout: this.config.system.redirectNavigationTimeout,
126
+ noHistory: true,
127
+ };
128
+ /**
129
+ * Default behavior is to redirect to the start page and not process the hash now.
130
+ * The start page is expected to also call handleRedirectPromise which will process the hash in one of the checks above.
131
+ */
132
+ let processHashOnRedirect = true;
133
+ if (!loginRequestUrl || loginRequestUrl === "null") {
134
+ // Redirect to home page if login request url is null (real null or the string null)
135
+ const homepage = getHomepage();
136
+ // Cache the homepage under ORIGIN_URI to ensure cached hash is processed on homepage
137
+ this.browserStorage.setTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, homepage, true);
138
+ this.logger.warning("Unable to get valid login request url from cache, redirecting to home page");
139
+ processHashOnRedirect =
140
+ await this.navigationClient.navigateInternal(homepage, navigationOptions);
141
+ }
142
+ else {
143
+ // Navigate to page that initiated the redirect request
144
+ this.logger.verbose(`Navigating to loginRequestUrl: ${loginRequestUrl}`);
145
+ processHashOnRedirect =
146
+ await this.navigationClient.navigateInternal(loginRequestUrl, navigationOptions);
147
+ }
148
+ // If navigateInternal implementation returns false, handle the hash now
149
+ if (!processHashOnRedirect) {
150
+ return await this.handleResponse(serverParams, serverTelemetryManager);
151
+ }
152
+ }
153
+ return null;
154
+ }
155
+ catch (e) {
156
+ if (e instanceof AuthError) {
157
+ e.setCorrelationId(this.correlationId);
158
+ serverTelemetryManager.cacheFailedRequest(e);
159
+ }
160
+ this.browserStorage.cleanRequestByInteractionType(InteractionType.Redirect);
161
+ throw e;
162
+ }
163
+ }
164
+ /**
165
+ * Gets the response hash for a redirect request
166
+ * Returns null if interactionType in the state value is not "redirect" or the hash does not contain known properties
167
+ * @param hash
168
+ */
169
+ getRedirectResponse(userProvidedResponse) {
170
+ this.logger.verbose("getRedirectResponseHash called");
171
+ // Get current location hash from window or cache.
172
+ let responseString = userProvidedResponse;
173
+ if (!responseString) {
174
+ if (this.config.auth.OIDCOptions.serverResponseType ===
175
+ ServerResponseType.QUERY) {
176
+ responseString = window.location.search;
177
+ }
178
+ else {
179
+ responseString = window.location.hash;
180
+ }
181
+ }
182
+ let response = UrlUtils.getDeserializedResponse(responseString);
183
+ if (response) {
184
+ try {
185
+ validateInteractionType(response, this.browserCrypto, InteractionType.Redirect);
186
+ }
187
+ catch (e) {
188
+ if (e instanceof AuthError) {
189
+ this.logger.error(`Interaction type validation failed due to ${e.errorCode}: ${e.errorMessage}`);
190
+ }
191
+ return [null, ""];
192
+ }
193
+ clearHash(window);
194
+ this.logger.verbose("Hash contains known properties, returning response hash");
195
+ return [response, responseString];
196
+ }
197
+ const cachedHash = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.URL_HASH, true);
198
+ this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.URL_HASH));
199
+ if (cachedHash) {
200
+ response = UrlUtils.getDeserializedResponse(cachedHash);
201
+ if (response) {
202
+ this.logger.verbose("Hash does not contain known properties, returning cached hash");
203
+ return [response, cachedHash];
204
+ }
205
+ }
206
+ return [null, ""];
207
+ }
208
+ /**
209
+ * Checks if hash exists and handles in window.
210
+ * @param hash
211
+ * @param state
212
+ */
213
+ async handleResponse(serverParams, serverTelemetryManager) {
214
+ const state = serverParams.state;
215
+ if (!state) {
216
+ throw createBrowserAuthError(noStateInHash);
217
+ }
218
+ const cachedRequest = this.browserStorage.getCachedRequest(state);
219
+ this.logger.verbose("handleResponse called, retrieved cached request");
220
+ if (serverParams.accountId) {
221
+ this.logger.verbose("Account id found in hash, calling WAM for token");
222
+ if (!this.nativeMessageHandler) {
223
+ throw createBrowserAuthError(nativeConnectionNotEstablished);
224
+ }
225
+ const nativeInteractionClient = new NativeInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenPopup, this.performanceClient, this.nativeMessageHandler, serverParams.accountId, this.nativeStorage, cachedRequest.correlationId);
226
+ const { userRequestState } = ProtocolUtils.parseRequestState(this.browserCrypto, state);
227
+ return nativeInteractionClient
228
+ .acquireToken({
229
+ ...cachedRequest,
230
+ state: userRequestState,
231
+ prompt: undefined, // Server should handle the prompt, ideally native broker can do this part silently
232
+ })
233
+ .finally(() => {
234
+ this.browserStorage.cleanRequestByState(state);
235
+ });
236
+ }
237
+ // Hash contains known properties - handle and return in callback
238
+ const currentAuthority = this.browserStorage.getCachedAuthority(state);
239
+ if (!currentAuthority) {
240
+ throw createBrowserAuthError(noCachedAuthorityError);
241
+ }
242
+ const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)(serverTelemetryManager, currentAuthority);
243
+ ThrottlingUtils.removeThrottle(this.browserStorage, this.config.auth.clientId, cachedRequest);
244
+ const interactionHandler = new RedirectHandler(authClient, this.browserStorage, cachedRequest, this.logger, this.performanceClient);
245
+ return interactionHandler.handleCodeResponse(serverParams, state);
246
+ }
247
+ /**
248
+ * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
249
+ * Default behaviour is to redirect the user to `window.location.href`.
250
+ * @param logoutRequest
251
+ */
252
+ async logout(logoutRequest) {
253
+ this.logger.verbose("logoutRedirect called");
254
+ const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
255
+ const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.logout);
256
+ try {
257
+ this.eventHandler.emitEvent(EventType.LOGOUT_START, InteractionType.Redirect, logoutRequest);
258
+ // Clear cache on logout
259
+ await this.clearCacheOnLogout(validLogoutRequest.account);
260
+ const navigationOptions = {
261
+ apiId: ApiId.logout,
262
+ timeout: this.config.system.redirectNavigationTimeout,
263
+ noHistory: false,
264
+ };
265
+ const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)(serverTelemetryManager, logoutRequest && logoutRequest.authority, undefined, // AzureCloudOptions
266
+ (logoutRequest && logoutRequest.account) || undefined);
267
+ if (authClient.authority.protocolMode === ProtocolMode.OIDC) {
268
+ try {
269
+ authClient.authority.endSessionEndpoint;
270
+ }
271
+ catch {
272
+ if (validLogoutRequest.account?.homeAccountId) {
273
+ void this.browserStorage.removeAccount(validLogoutRequest.account?.homeAccountId);
274
+ this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, InteractionType.Redirect, validLogoutRequest);
275
+ return;
276
+ }
277
+ }
278
+ }
279
+ // Create logout string and navigate user window to logout.
280
+ const logoutUri = authClient.getLogoutUri(validLogoutRequest);
281
+ this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, InteractionType.Redirect, validLogoutRequest);
282
+ // Check if onRedirectNavigate is implemented, and invoke it if so
283
+ if (logoutRequest &&
284
+ typeof logoutRequest.onRedirectNavigate === "function") {
285
+ const navigate = logoutRequest.onRedirectNavigate(logoutUri);
286
+ if (navigate !== false) {
287
+ this.logger.verbose("Logout onRedirectNavigate did not return false, navigating");
288
+ // Ensure interaction is in progress
289
+ if (!this.browserStorage.getInteractionInProgress()) {
290
+ this.browserStorage.setInteractionInProgress(true);
291
+ }
292
+ await this.navigationClient.navigateExternal(logoutUri, navigationOptions);
293
+ return;
294
+ }
295
+ else {
296
+ // Ensure interaction is not in progress
297
+ this.browserStorage.setInteractionInProgress(false);
298
+ this.logger.verbose("Logout onRedirectNavigate returned false, stopping navigation");
299
+ }
300
+ }
301
+ else {
302
+ // Ensure interaction is in progress
303
+ if (!this.browserStorage.getInteractionInProgress()) {
304
+ this.browserStorage.setInteractionInProgress(true);
305
+ }
306
+ await this.navigationClient.navigateExternal(logoutUri, navigationOptions);
307
+ return;
308
+ }
309
+ }
310
+ catch (e) {
311
+ if (e instanceof AuthError) {
312
+ e.setCorrelationId(this.correlationId);
313
+ serverTelemetryManager.cacheFailedRequest(e);
314
+ }
315
+ this.eventHandler.emitEvent(EventType.LOGOUT_FAILURE, InteractionType.Redirect, null, e);
316
+ this.eventHandler.emitEvent(EventType.LOGOUT_END, InteractionType.Redirect);
317
+ throw e;
318
+ }
319
+ this.eventHandler.emitEvent(EventType.LOGOUT_END, InteractionType.Redirect);
320
+ }
321
+ /**
322
+ * Use to get the redirectStartPage either from request or use current window
323
+ * @param requestStartPage
324
+ */
325
+ getRedirectStartPage(requestStartPage) {
326
+ const redirectStartPage = requestStartPage || window.location.href;
327
+ return UrlString.getAbsoluteUrl(redirectStartPage, getCurrentUri());
328
+ }
328
329
  }
329
330
 
330
331
  export { RedirectClient };