@azure/msal-node 2.0.2 → 2.2.0-alpha.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 (218) hide show
  1. package/README.md +3 -1
  2. package/dist/cache/ITokenCache.d.ts +15 -15
  3. package/dist/cache/NodeStorage.cjs +401 -401
  4. package/dist/cache/NodeStorage.cjs.map +1 -1
  5. package/dist/cache/NodeStorage.d.ts +182 -182
  6. package/dist/cache/NodeStorage.d.ts.map +1 -1
  7. package/dist/cache/NodeStorage.mjs +401 -401
  8. package/dist/cache/NodeStorage.mjs.map +1 -1
  9. package/dist/cache/TokenCache.cjs +265 -269
  10. package/dist/cache/TokenCache.cjs.map +1 -1
  11. package/dist/cache/TokenCache.d.ts +90 -90
  12. package/dist/cache/TokenCache.d.ts.map +1 -1
  13. package/dist/cache/TokenCache.mjs +266 -270
  14. package/dist/cache/TokenCache.mjs.map +1 -1
  15. package/dist/cache/distributed/DistributedCachePlugin.cjs +26 -26
  16. package/dist/cache/distributed/DistributedCachePlugin.cjs.map +1 -1
  17. package/dist/cache/distributed/DistributedCachePlugin.d.ts +10 -10
  18. package/dist/cache/distributed/DistributedCachePlugin.d.ts.map +1 -1
  19. package/dist/cache/distributed/DistributedCachePlugin.mjs +26 -26
  20. package/dist/cache/distributed/DistributedCachePlugin.mjs.map +1 -1
  21. package/dist/cache/distributed/ICacheClient.d.ts +17 -17
  22. package/dist/cache/distributed/IPartitionManager.d.ts +28 -28
  23. package/dist/cache/serializer/Deserializer.cjs +173 -175
  24. package/dist/cache/serializer/Deserializer.cjs.map +1 -1
  25. package/dist/cache/serializer/Deserializer.d.ts +42 -42
  26. package/dist/cache/serializer/Deserializer.d.ts.map +1 -1
  27. package/dist/cache/serializer/Deserializer.mjs +174 -176
  28. package/dist/cache/serializer/Deserializer.mjs.map +1 -1
  29. package/dist/cache/serializer/Serializer.cjs +134 -134
  30. package/dist/cache/serializer/Serializer.cjs.map +1 -1
  31. package/dist/cache/serializer/Serializer.d.ts +39 -39
  32. package/dist/cache/serializer/Serializer.d.ts.map +1 -1
  33. package/dist/cache/serializer/Serializer.mjs +134 -134
  34. package/dist/cache/serializer/Serializer.mjs.map +1 -1
  35. package/dist/cache/serializer/SerializerTypes.d.ts +101 -101
  36. package/dist/client/ClientApplication.cjs +333 -333
  37. package/dist/client/ClientApplication.cjs.map +1 -1
  38. package/dist/client/ClientApplication.d.ts +142 -142
  39. package/dist/client/ClientApplication.d.ts.map +1 -1
  40. package/dist/client/ClientApplication.mjs +334 -334
  41. package/dist/client/ClientApplication.mjs.map +1 -1
  42. package/dist/client/ClientAssertion.cjs +116 -116
  43. package/dist/client/ClientAssertion.cjs.map +1 -1
  44. package/dist/client/ClientAssertion.d.ts +46 -46
  45. package/dist/client/ClientAssertion.d.ts.map +1 -1
  46. package/dist/client/ClientAssertion.mjs +117 -117
  47. package/dist/client/ClientAssertion.mjs.map +1 -1
  48. package/dist/client/ClientCredentialClient.cjs +189 -168
  49. package/dist/client/ClientCredentialClient.cjs.map +1 -1
  50. package/dist/client/ClientCredentialClient.d.ts +33 -33
  51. package/dist/client/ClientCredentialClient.d.ts.map +1 -1
  52. package/dist/client/ClientCredentialClient.mjs +190 -169
  53. package/dist/client/ClientCredentialClient.mjs.map +1 -1
  54. package/dist/client/ConfidentialClientApplication.cjs +163 -164
  55. package/dist/client/ConfidentialClientApplication.cjs.map +1 -1
  56. package/dist/client/ConfidentialClientApplication.d.ts +58 -58
  57. package/dist/client/ConfidentialClientApplication.d.ts.map +1 -1
  58. package/dist/client/ConfidentialClientApplication.mjs +164 -165
  59. package/dist/client/ConfidentialClientApplication.mjs.map +1 -1
  60. package/dist/client/DeviceCodeClient.cjs +207 -207
  61. package/dist/client/DeviceCodeClient.cjs.map +1 -1
  62. package/dist/client/DeviceCodeClient.d.ts +53 -53
  63. package/dist/client/DeviceCodeClient.d.ts.map +1 -1
  64. package/dist/client/DeviceCodeClient.mjs +208 -208
  65. package/dist/client/DeviceCodeClient.mjs.map +1 -1
  66. package/dist/client/IConfidentialClientApplication.d.ts +39 -39
  67. package/dist/client/IConfidentialClientApplication.d.ts.map +1 -1
  68. package/dist/client/IPublicClientApplication.d.ts +42 -42
  69. package/dist/client/IPublicClientApplication.d.ts.map +1 -1
  70. package/dist/client/OnBehalfOfClient.cjs +203 -204
  71. package/dist/client/OnBehalfOfClient.cjs.map +1 -1
  72. package/dist/client/OnBehalfOfClient.d.ts +47 -47
  73. package/dist/client/OnBehalfOfClient.d.ts.map +1 -1
  74. package/dist/client/OnBehalfOfClient.mjs +204 -205
  75. package/dist/client/OnBehalfOfClient.mjs.map +1 -1
  76. package/dist/client/PublicClientApplication.cjs +229 -175
  77. package/dist/client/PublicClientApplication.cjs.map +1 -1
  78. package/dist/client/PublicClientApplication.d.ts +71 -65
  79. package/dist/client/PublicClientApplication.d.ts.map +1 -1
  80. package/dist/client/PublicClientApplication.mjs +232 -178
  81. package/dist/client/PublicClientApplication.mjs.map +1 -1
  82. package/dist/client/UsernamePasswordClient.cjs +95 -95
  83. package/dist/client/UsernamePasswordClient.cjs.map +1 -1
  84. package/dist/client/UsernamePasswordClient.d.ts +25 -25
  85. package/dist/client/UsernamePasswordClient.d.ts.map +1 -1
  86. package/dist/client/UsernamePasswordClient.mjs +95 -95
  87. package/dist/client/UsernamePasswordClient.mjs.map +1 -1
  88. package/dist/config/Configuration.cjs +72 -72
  89. package/dist/config/Configuration.cjs.map +1 -1
  90. package/dist/config/Configuration.d.ts +107 -107
  91. package/dist/config/Configuration.mjs +72 -72
  92. package/dist/config/Configuration.mjs.map +1 -1
  93. package/dist/crypto/CryptoProvider.cjs +75 -75
  94. package/dist/crypto/CryptoProvider.cjs.map +1 -1
  95. package/dist/crypto/CryptoProvider.d.ts +52 -52
  96. package/dist/crypto/CryptoProvider.mjs +75 -75
  97. package/dist/crypto/CryptoProvider.mjs.map +1 -1
  98. package/dist/crypto/GuidGenerator.cjs +22 -22
  99. package/dist/crypto/GuidGenerator.cjs.map +1 -1
  100. package/dist/crypto/GuidGenerator.d.ts +14 -14
  101. package/dist/crypto/GuidGenerator.mjs +22 -22
  102. package/dist/crypto/GuidGenerator.mjs.map +1 -1
  103. package/dist/crypto/HashUtils.cjs +13 -13
  104. package/dist/crypto/HashUtils.cjs.map +1 -1
  105. package/dist/crypto/HashUtils.d.ts +8 -8
  106. package/dist/crypto/HashUtils.mjs +13 -13
  107. package/dist/crypto/HashUtils.mjs.map +1 -1
  108. package/dist/crypto/PkceGenerator.cjs +49 -49
  109. package/dist/crypto/PkceGenerator.cjs.map +1 -1
  110. package/dist/crypto/PkceGenerator.d.ts +22 -22
  111. package/dist/crypto/PkceGenerator.mjs +49 -49
  112. package/dist/crypto/PkceGenerator.mjs.map +1 -1
  113. package/dist/error/NodeAuthError.cjs +85 -85
  114. package/dist/error/NodeAuthError.cjs.map +1 -1
  115. package/dist/error/NodeAuthError.d.ts +65 -65
  116. package/dist/error/NodeAuthError.mjs +85 -85
  117. package/dist/error/NodeAuthError.mjs.map +1 -1
  118. package/dist/index.cjs +17 -1
  119. package/dist/index.cjs.map +1 -1
  120. package/dist/index.d.ts +42 -42
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.mjs +2 -2
  123. package/dist/internals.cjs +8 -8
  124. package/dist/internals.cjs.map +1 -1
  125. package/dist/internals.d.ts +6 -6
  126. package/dist/internals.d.ts.map +1 -1
  127. package/dist/internals.mjs +8 -8
  128. package/dist/internals.mjs.map +1 -1
  129. package/dist/network/HttpClient.cjs +277 -276
  130. package/dist/network/HttpClient.cjs.map +1 -1
  131. package/dist/network/HttpClient.d.ts +25 -25
  132. package/dist/network/HttpClient.d.ts.map +1 -1
  133. package/dist/network/HttpClient.mjs +278 -277
  134. package/dist/network/HttpClient.mjs.map +1 -1
  135. package/dist/network/ILoopbackClient.d.ts +10 -10
  136. package/dist/network/LoopbackClient.cjs +75 -84
  137. package/dist/network/LoopbackClient.cjs.map +1 -1
  138. package/dist/network/LoopbackClient.d.ts +21 -21
  139. package/dist/network/LoopbackClient.d.ts.map +1 -1
  140. package/dist/network/LoopbackClient.mjs +77 -86
  141. package/dist/network/LoopbackClient.mjs.map +1 -1
  142. package/dist/packageMetadata.cjs +4 -4
  143. package/dist/packageMetadata.cjs.map +1 -1
  144. package/dist/packageMetadata.d.ts +2 -2
  145. package/dist/packageMetadata.mjs +4 -4
  146. package/dist/packageMetadata.mjs.map +1 -1
  147. package/dist/request/AuthorizationCodeRequest.d.ts +21 -21
  148. package/dist/request/AuthorizationUrlRequest.d.ts +33 -33
  149. package/dist/request/ClientCredentialRequest.d.ts +14 -14
  150. package/dist/request/DeviceCodeRequest.d.ts +15 -15
  151. package/dist/request/InteractiveRequest.d.ts +22 -22
  152. package/dist/request/InteractiveRequest.d.ts.map +1 -1
  153. package/dist/request/OnBehalfOfRequest.d.ts +14 -14
  154. package/dist/request/RefreshTokenRequest.d.ts +17 -17
  155. package/dist/request/SignOutRequest.d.ts +5 -5
  156. package/dist/request/SilentFlowRequest.d.ts +16 -16
  157. package/dist/request/UsernamePasswordRequest.d.ts +19 -19
  158. package/dist/utils/Constants.cjs +80 -90
  159. package/dist/utils/Constants.cjs.map +1 -1
  160. package/dist/utils/Constants.d.ts +86 -96
  161. package/dist/utils/Constants.d.ts.map +1 -1
  162. package/dist/utils/Constants.mjs +81 -90
  163. package/dist/utils/Constants.mjs.map +1 -1
  164. package/dist/utils/EncodingUtils.cjs +44 -44
  165. package/dist/utils/EncodingUtils.cjs.map +1 -1
  166. package/dist/utils/EncodingUtils.d.ts +26 -26
  167. package/dist/utils/EncodingUtils.mjs +44 -44
  168. package/dist/utils/EncodingUtils.mjs.map +1 -1
  169. package/dist/utils/NetworkUtils.cjs +38 -38
  170. package/dist/utils/NetworkUtils.cjs.map +1 -1
  171. package/dist/utils/NetworkUtils.d.ts +5 -5
  172. package/dist/utils/NetworkUtils.mjs +38 -38
  173. package/dist/utils/NetworkUtils.mjs.map +1 -1
  174. package/package.json +8 -5
  175. package/src/cache/ITokenCache.ts +24 -0
  176. package/src/cache/NodeStorage.ts +533 -0
  177. package/src/cache/TokenCache.ts +358 -0
  178. package/src/cache/distributed/DistributedCachePlugin.ts +56 -0
  179. package/src/cache/distributed/ICacheClient.ts +23 -0
  180. package/src/cache/distributed/IPartitionManager.ts +35 -0
  181. package/src/cache/serializer/Deserializer.ts +218 -0
  182. package/src/cache/serializer/Serializer.ts +173 -0
  183. package/src/cache/serializer/SerializerTypes.ts +121 -0
  184. package/src/client/ClientApplication.ts +596 -0
  185. package/src/client/ClientAssertion.ts +165 -0
  186. package/src/client/ClientCredentialClient.ts +346 -0
  187. package/src/client/ConfidentialClientApplication.ts +268 -0
  188. package/src/client/DeviceCodeClient.ts +369 -0
  189. package/src/client/IConfidentialClientApplication.ts +72 -0
  190. package/src/client/IPublicClientApplication.ts +72 -0
  191. package/src/client/OnBehalfOfClient.ts +368 -0
  192. package/src/client/PublicClientApplication.ts +339 -0
  193. package/src/client/UsernamePasswordClient.ts +180 -0
  194. package/src/config/Configuration.ts +201 -0
  195. package/src/crypto/CryptoProvider.ts +98 -0
  196. package/src/crypto/GuidGenerator.ts +28 -0
  197. package/src/crypto/HashUtils.ts +17 -0
  198. package/src/crypto/PkceGenerator.ts +63 -0
  199. package/src/error/NodeAuthError.ts +117 -0
  200. package/src/index.ts +125 -0
  201. package/src/internals.ts +12 -0
  202. package/src/network/HttpClient.ts +425 -0
  203. package/src/network/ILoopbackClient.ts +19 -0
  204. package/src/network/LoopbackClient.ts +110 -0
  205. package/src/packageMetadata.ts +3 -0
  206. package/src/request/AuthorizationCodeRequest.ts +39 -0
  207. package/src/request/AuthorizationUrlRequest.ts +50 -0
  208. package/src/request/ClientCredentialRequest.ts +29 -0
  209. package/src/request/DeviceCodeRequest.ts +34 -0
  210. package/src/request/InteractiveRequest.ts +39 -0
  211. package/src/request/OnBehalfOfRequest.ts +30 -0
  212. package/src/request/RefreshTokenRequest.ts +34 -0
  213. package/src/request/SignOutRequest.ts +11 -0
  214. package/src/request/SilentFlowRequest.ts +32 -0
  215. package/src/request/UsernamePasswordRequest.ts +36 -0
  216. package/src/utils/Constants.ts +103 -0
  217. package/src/utils/EncodingUtils.ts +50 -0
  218. package/src/utils/NetworkUtils.ts +49 -0
@@ -0,0 +1,596 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import {
7
+ AuthorizationCodeClient,
8
+ ClientConfiguration,
9
+ RefreshTokenClient,
10
+ AuthenticationResult,
11
+ Authority,
12
+ AuthorityFactory,
13
+ BaseAuthRequest,
14
+ SilentFlowClient,
15
+ Logger,
16
+ ServerTelemetryManager,
17
+ ServerTelemetryRequest,
18
+ CommonSilentFlowRequest,
19
+ CommonRefreshTokenRequest,
20
+ CommonAuthorizationCodeRequest,
21
+ CommonAuthorizationUrlRequest,
22
+ CommonUsernamePasswordRequest,
23
+ AuthenticationScheme,
24
+ ResponseMode,
25
+ AuthorityOptions,
26
+ OIDC_DEFAULT_SCOPES,
27
+ AzureRegionConfiguration,
28
+ AuthError,
29
+ AzureCloudOptions,
30
+ AuthorizationCodePayload,
31
+ Constants,
32
+ StringUtils,
33
+ createClientAuthError,
34
+ ClientAuthErrorCodes,
35
+ } from "@azure/msal-common";
36
+ import {
37
+ Configuration,
38
+ buildAppConfiguration,
39
+ NodeConfiguration,
40
+ } from "../config/Configuration.js";
41
+ import { CryptoProvider } from "../crypto/CryptoProvider.js";
42
+ import { NodeStorage } from "../cache/NodeStorage.js";
43
+ import { Constants as NodeConstants, ApiId } from "../utils/Constants.js";
44
+ import { TokenCache } from "../cache/TokenCache.js";
45
+ import { ClientAssertion } from "./ClientAssertion.js";
46
+ import { AuthorizationUrlRequest } from "../request/AuthorizationUrlRequest.js";
47
+ import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest.js";
48
+ import { RefreshTokenRequest } from "../request/RefreshTokenRequest.js";
49
+ import { SilentFlowRequest } from "../request/SilentFlowRequest.js";
50
+ import { version, name } from "../packageMetadata.js";
51
+ import { UsernamePasswordRequest } from "../request/UsernamePasswordRequest.js";
52
+ import { NodeAuthError } from "../error/NodeAuthError.js";
53
+ import { UsernamePasswordClient } from "./UsernamePasswordClient.js";
54
+
55
+ /**
56
+ * Base abstract class for all ClientApplications - public and confidential
57
+ * @public
58
+ */
59
+ export abstract class ClientApplication {
60
+ protected readonly cryptoProvider: CryptoProvider;
61
+ private tokenCache: TokenCache;
62
+
63
+ /**
64
+ * Platform storage object
65
+ */
66
+ protected storage: NodeStorage;
67
+ /**
68
+ * Logger object to log the application flow
69
+ */
70
+ protected logger: Logger;
71
+ /**
72
+ * Platform configuration initialized by the application
73
+ */
74
+ protected config: NodeConfiguration;
75
+ /**
76
+ * Client assertion passed by the user for confidential client flows
77
+ */
78
+ protected clientAssertion: ClientAssertion;
79
+ /**
80
+ * Client secret passed by the user for confidential client flows
81
+ */
82
+ protected clientSecret: string;
83
+
84
+ /**
85
+ * Constructor for the ClientApplication
86
+ */
87
+ protected constructor(configuration: Configuration) {
88
+ this.config = buildAppConfiguration(configuration);
89
+ this.cryptoProvider = new CryptoProvider();
90
+ this.logger = new Logger(
91
+ this.config.system.loggerOptions,
92
+ name,
93
+ version
94
+ );
95
+ this.storage = new NodeStorage(
96
+ this.logger,
97
+ this.config.auth.clientId,
98
+ this.cryptoProvider
99
+ );
100
+ this.tokenCache = new TokenCache(
101
+ this.storage,
102
+ this.logger,
103
+ this.config.cache.cachePlugin
104
+ );
105
+ }
106
+
107
+ /**
108
+ * Creates the URL of the authorization request, letting the user input credentials and consent to the
109
+ * application. The URL targets the /authorize endpoint of the authority configured in the
110
+ * application object.
111
+ *
112
+ * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
113
+ * sent in the request and should contain an authorization code, which can then be used to acquire tokens via
114
+ * `acquireTokenByCode(AuthorizationCodeRequest)`.
115
+ */
116
+ async getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string> {
117
+ this.logger.info("getAuthCodeUrl called", request.correlationId);
118
+ const validRequest: CommonAuthorizationUrlRequest = {
119
+ ...request,
120
+ ...(await this.initializeBaseRequest(request)),
121
+ responseMode: request.responseMode || ResponseMode.QUERY,
122
+ authenticationScheme: AuthenticationScheme.BEARER,
123
+ };
124
+
125
+ const authClientConfig = await this.buildOauthClientConfiguration(
126
+ validRequest.authority,
127
+ validRequest.correlationId,
128
+ undefined,
129
+ undefined,
130
+ request.azureCloudOptions
131
+ );
132
+ const authorizationCodeClient = new AuthorizationCodeClient(
133
+ authClientConfig
134
+ );
135
+ this.logger.verbose(
136
+ "Auth code client created",
137
+ validRequest.correlationId
138
+ );
139
+ return authorizationCodeClient.getAuthCodeUrl(validRequest);
140
+ }
141
+
142
+ /**
143
+ * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0
144
+ * Authorization Code flow.
145
+ *
146
+ * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0
147
+ * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and
148
+ * AuthorizationCodeRequest are the same.
149
+ */
150
+ async acquireTokenByCode(
151
+ request: AuthorizationCodeRequest,
152
+ authCodePayLoad?: AuthorizationCodePayload
153
+ ): Promise<AuthenticationResult> {
154
+ this.logger.info("acquireTokenByCode called");
155
+ if (request.state && authCodePayLoad) {
156
+ this.logger.info("acquireTokenByCode - validating state");
157
+ this.validateState(request.state, authCodePayLoad.state || "");
158
+ // eslint-disable-next-line no-param-reassign
159
+ authCodePayLoad = { ...authCodePayLoad, state: "" };
160
+ }
161
+ const validRequest: CommonAuthorizationCodeRequest = {
162
+ ...request,
163
+ ...(await this.initializeBaseRequest(request)),
164
+ authenticationScheme: AuthenticationScheme.BEARER,
165
+ };
166
+
167
+ const serverTelemetryManager = this.initializeServerTelemetryManager(
168
+ ApiId.acquireTokenByCode,
169
+ validRequest.correlationId
170
+ );
171
+ try {
172
+ const authClientConfig = await this.buildOauthClientConfiguration(
173
+ validRequest.authority,
174
+ validRequest.correlationId,
175
+ serverTelemetryManager,
176
+ undefined,
177
+ request.azureCloudOptions
178
+ );
179
+ const authorizationCodeClient = new AuthorizationCodeClient(
180
+ authClientConfig
181
+ );
182
+ this.logger.verbose(
183
+ "Auth code client created",
184
+ validRequest.correlationId
185
+ );
186
+ return authorizationCodeClient.acquireToken(
187
+ validRequest,
188
+ authCodePayLoad
189
+ );
190
+ } catch (e) {
191
+ if (e instanceof AuthError) {
192
+ e.setCorrelationId(validRequest.correlationId);
193
+ }
194
+ serverTelemetryManager.cacheFailedRequest(e);
195
+ throw e;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Acquires a token by exchanging the refresh token provided for a new set of tokens.
201
+ *
202
+ * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is
203
+ * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will
204
+ * handle the caching and refreshing of tokens automatically.
205
+ */
206
+ async acquireTokenByRefreshToken(
207
+ request: RefreshTokenRequest
208
+ ): Promise<AuthenticationResult | null> {
209
+ this.logger.info(
210
+ "acquireTokenByRefreshToken called",
211
+ request.correlationId
212
+ );
213
+ const validRequest: CommonRefreshTokenRequest = {
214
+ ...request,
215
+ ...(await this.initializeBaseRequest(request)),
216
+ authenticationScheme: AuthenticationScheme.BEARER,
217
+ };
218
+
219
+ const serverTelemetryManager = this.initializeServerTelemetryManager(
220
+ ApiId.acquireTokenByRefreshToken,
221
+ validRequest.correlationId
222
+ );
223
+ try {
224
+ const refreshTokenClientConfig =
225
+ await this.buildOauthClientConfiguration(
226
+ validRequest.authority,
227
+ validRequest.correlationId,
228
+ serverTelemetryManager,
229
+ undefined,
230
+ request.azureCloudOptions
231
+ );
232
+ const refreshTokenClient = new RefreshTokenClient(
233
+ refreshTokenClientConfig
234
+ );
235
+ this.logger.verbose(
236
+ "Refresh token client created",
237
+ validRequest.correlationId
238
+ );
239
+ return refreshTokenClient.acquireToken(validRequest);
240
+ } catch (e) {
241
+ if (e instanceof AuthError) {
242
+ e.setCorrelationId(validRequest.correlationId);
243
+ }
244
+ serverTelemetryManager.cacheFailedRequest(e);
245
+ throw e;
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Acquires a token silently when a user specifies the account the token is requested for.
251
+ *
252
+ * This API expects the user to provide an account object and looks into the cache to retrieve the token if present.
253
+ * There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token.
254
+ * In case the refresh_token is expired or not found, an error is thrown
255
+ * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).
256
+ */
257
+ async acquireTokenSilent(
258
+ request: SilentFlowRequest
259
+ ): Promise<AuthenticationResult> {
260
+ const validRequest: CommonSilentFlowRequest = {
261
+ ...request,
262
+ ...(await this.initializeBaseRequest(request)),
263
+ forceRefresh: request.forceRefresh || false,
264
+ };
265
+
266
+ const serverTelemetryManager = this.initializeServerTelemetryManager(
267
+ ApiId.acquireTokenSilent,
268
+ validRequest.correlationId,
269
+ validRequest.forceRefresh
270
+ );
271
+ try {
272
+ const silentFlowClientConfig =
273
+ await this.buildOauthClientConfiguration(
274
+ validRequest.authority,
275
+ validRequest.correlationId,
276
+ serverTelemetryManager,
277
+ undefined,
278
+ request.azureCloudOptions
279
+ );
280
+ const silentFlowClient = new SilentFlowClient(
281
+ silentFlowClientConfig
282
+ );
283
+ this.logger.verbose(
284
+ "Silent flow client created",
285
+ validRequest.correlationId
286
+ );
287
+ return silentFlowClient.acquireToken(validRequest);
288
+ } catch (e) {
289
+ if (e instanceof AuthError) {
290
+ e.setCorrelationId(validRequest.correlationId);
291
+ }
292
+ serverTelemetryManager.cacheFailedRequest(e as AuthError);
293
+ throw e;
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Acquires tokens with password grant by exchanging client applications username and password for credentials
299
+ *
300
+ * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.
301
+ * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4
302
+ * Microsoft's documentation and recommendations are at:
303
+ * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword
304
+ *
305
+ * @param request - UsenamePasswordRequest
306
+ */
307
+ async acquireTokenByUsernamePassword(
308
+ request: UsernamePasswordRequest
309
+ ): Promise<AuthenticationResult | null> {
310
+ this.logger.info(
311
+ "acquireTokenByUsernamePassword called",
312
+ request.correlationId
313
+ );
314
+ const validRequest: CommonUsernamePasswordRequest = {
315
+ ...request,
316
+ ...(await this.initializeBaseRequest(request)),
317
+ };
318
+ const serverTelemetryManager = this.initializeServerTelemetryManager(
319
+ ApiId.acquireTokenByUsernamePassword,
320
+ validRequest.correlationId
321
+ );
322
+ try {
323
+ const usernamePasswordClientConfig =
324
+ await this.buildOauthClientConfiguration(
325
+ validRequest.authority,
326
+ validRequest.correlationId,
327
+ serverTelemetryManager,
328
+ undefined,
329
+ request.azureCloudOptions
330
+ );
331
+ const usernamePasswordClient = new UsernamePasswordClient(
332
+ usernamePasswordClientConfig
333
+ );
334
+ this.logger.verbose(
335
+ "Username password client created",
336
+ validRequest.correlationId
337
+ );
338
+ return usernamePasswordClient.acquireToken(validRequest);
339
+ } catch (e) {
340
+ if (e instanceof AuthError) {
341
+ e.setCorrelationId(validRequest.correlationId);
342
+ }
343
+ serverTelemetryManager.cacheFailedRequest(e);
344
+ throw e;
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Gets the token cache for the application.
350
+ */
351
+ getTokenCache(): TokenCache {
352
+ this.logger.info("getTokenCache called");
353
+ return this.tokenCache;
354
+ }
355
+
356
+ /**
357
+ * Validates OIDC state by comparing the user cached state with the state received from the server.
358
+ *
359
+ * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against
360
+ * CSRF attacks.
361
+ * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.
362
+ * @param state
363
+ * @param cachedState
364
+ */
365
+ protected validateState(state: string, cachedState: string): void {
366
+ if (!state) {
367
+ throw NodeAuthError.createStateNotFoundError();
368
+ }
369
+
370
+ if (state !== cachedState) {
371
+ throw createClientAuthError(ClientAuthErrorCodes.stateMismatch);
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Returns the logger instance
377
+ */
378
+ getLogger(): Logger {
379
+ return this.logger;
380
+ }
381
+
382
+ /**
383
+ * Replaces the default logger set in configurations with new Logger with new configurations
384
+ * @param logger - Logger instance
385
+ */
386
+ setLogger(logger: Logger): void {
387
+ this.logger = logger;
388
+ }
389
+
390
+ /**
391
+ * Builds the common configuration to be passed to the common component based on the platform configurarion
392
+ * @param authority - user passed authority in configuration
393
+ * @param serverTelemetryManager - initializes servertelemetry if passed
394
+ */
395
+ protected async buildOauthClientConfiguration(
396
+ authority: string,
397
+ requestCorrelationId?: string,
398
+ serverTelemetryManager?: ServerTelemetryManager,
399
+ azureRegionConfiguration?: AzureRegionConfiguration,
400
+ azureCloudOptions?: AzureCloudOptions
401
+ ): Promise<ClientConfiguration> {
402
+ this.logger.verbose(
403
+ "buildOauthClientConfiguration called",
404
+ requestCorrelationId
405
+ );
406
+
407
+ // precedence - azureCloudInstance + tenant >> authority and request >> config
408
+ const userAzureCloudOptions = azureCloudOptions
409
+ ? azureCloudOptions
410
+ : this.config.auth.azureCloudOptions;
411
+
412
+ // using null assertion operator as we ensure that all config values have default values in buildConfiguration()
413
+ this.logger.verbose(
414
+ `building oauth client configuration with the authority: ${authority}`,
415
+ requestCorrelationId
416
+ );
417
+ const discoveredAuthority = await this.createAuthority(
418
+ authority,
419
+ azureRegionConfiguration,
420
+ requestCorrelationId,
421
+ userAzureCloudOptions
422
+ );
423
+
424
+ serverTelemetryManager?.updateRegionDiscoveryMetadata(
425
+ discoveredAuthority.regionDiscoveryMetadata
426
+ );
427
+
428
+ const clientConfiguration: ClientConfiguration = {
429
+ authOptions: {
430
+ clientId: this.config.auth.clientId,
431
+ authority: discoveredAuthority,
432
+ clientCapabilities: this.config.auth.clientCapabilities,
433
+ },
434
+ loggerOptions: {
435
+ logLevel: this.config.system.loggerOptions.logLevel,
436
+ loggerCallback: this.config.system.loggerOptions.loggerCallback,
437
+ piiLoggingEnabled:
438
+ this.config.system.loggerOptions.piiLoggingEnabled,
439
+ correlationId: requestCorrelationId,
440
+ },
441
+ cacheOptions: {
442
+ claimsBasedCachingEnabled:
443
+ this.config.cache.claimsBasedCachingEnabled,
444
+ },
445
+ cryptoInterface: this.cryptoProvider,
446
+ networkInterface: this.config.system.networkClient,
447
+ storageInterface: this.storage,
448
+ serverTelemetryManager: serverTelemetryManager,
449
+ clientCredentials: {
450
+ clientSecret: this.clientSecret,
451
+ clientAssertion: this.clientAssertion
452
+ ? this.getClientAssertion(discoveredAuthority)
453
+ : undefined,
454
+ },
455
+ libraryInfo: {
456
+ sku: NodeConstants.MSAL_SKU,
457
+ version: version,
458
+ cpu: process.arch || Constants.EMPTY_STRING,
459
+ os: process.platform || Constants.EMPTY_STRING,
460
+ },
461
+ telemetry: this.config.telemetry,
462
+ persistencePlugin: this.config.cache.cachePlugin,
463
+ serializableCache: this.tokenCache,
464
+ };
465
+
466
+ return clientConfiguration;
467
+ }
468
+
469
+ private getClientAssertion(authority: Authority): {
470
+ assertion: string;
471
+ assertionType: string;
472
+ } {
473
+ return {
474
+ assertion: this.clientAssertion.getJwt(
475
+ this.cryptoProvider,
476
+ this.config.auth.clientId,
477
+ authority.tokenEndpoint
478
+ ),
479
+ assertionType: NodeConstants.JWT_BEARER_ASSERTION_TYPE,
480
+ };
481
+ }
482
+
483
+ /**
484
+ * Generates a request with the default scopes & generates a correlationId.
485
+ * @param authRequest - BaseAuthRequest for initialization
486
+ */
487
+ protected async initializeBaseRequest(
488
+ authRequest: Partial<BaseAuthRequest>
489
+ ): Promise<BaseAuthRequest> {
490
+ this.logger.verbose(
491
+ "initializeRequestScopes called",
492
+ authRequest.correlationId
493
+ );
494
+ // Default authenticationScheme to Bearer, log that POP isn't supported yet
495
+ if (
496
+ authRequest.authenticationScheme &&
497
+ authRequest.authenticationScheme === AuthenticationScheme.POP
498
+ ) {
499
+ this.logger.verbose(
500
+ "Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",
501
+ authRequest.correlationId
502
+ );
503
+ }
504
+
505
+ authRequest.authenticationScheme = AuthenticationScheme.BEARER;
506
+
507
+ // Set requested claims hash if claims-based caching is enabled and claims were requested
508
+ if (
509
+ this.config.cache.claimsBasedCachingEnabled &&
510
+ authRequest.claims &&
511
+ // Checks for empty stringified object "{}" which doesn't qualify as requested claims
512
+ !StringUtils.isEmptyObj(authRequest.claims)
513
+ ) {
514
+ authRequest.requestedClaimsHash =
515
+ await this.cryptoProvider.hashString(authRequest.claims);
516
+ }
517
+
518
+ return {
519
+ ...authRequest,
520
+ scopes: [
521
+ ...((authRequest && authRequest.scopes) || []),
522
+ ...OIDC_DEFAULT_SCOPES,
523
+ ],
524
+ correlationId:
525
+ (authRequest && authRequest.correlationId) ||
526
+ this.cryptoProvider.createNewGuid(),
527
+ authority: authRequest.authority || this.config.auth.authority,
528
+ };
529
+ }
530
+
531
+ /**
532
+ * Initializes the server telemetry payload
533
+ * @param apiId - Id for a specific request
534
+ * @param correlationId - GUID
535
+ * @param forceRefresh - boolean to indicate network call
536
+ */
537
+ protected initializeServerTelemetryManager(
538
+ apiId: number,
539
+ correlationId: string,
540
+ forceRefresh?: boolean
541
+ ): ServerTelemetryManager {
542
+ const telemetryPayload: ServerTelemetryRequest = {
543
+ clientId: this.config.auth.clientId,
544
+ correlationId: correlationId,
545
+ apiId: apiId,
546
+ forceRefresh: forceRefresh || false,
547
+ };
548
+
549
+ return new ServerTelemetryManager(telemetryPayload, this.storage);
550
+ }
551
+
552
+ /**
553
+ * Create authority instance. If authority not passed in request, default to authority set on the application
554
+ * object. If no authority set in application object, then default to common authority.
555
+ * @param authorityString - authority from user configuration
556
+ */
557
+ private async createAuthority(
558
+ authorityString: string,
559
+ azureRegionConfiguration?: AzureRegionConfiguration,
560
+ requestCorrelationId?: string,
561
+ azureCloudOptions?: AzureCloudOptions
562
+ ): Promise<Authority> {
563
+ this.logger.verbose("createAuthority called", requestCorrelationId);
564
+
565
+ // build authority string based on auth params - azureCloudInstance is prioritized if provided
566
+ const authorityUrl = Authority.generateAuthority(
567
+ authorityString,
568
+ azureCloudOptions
569
+ );
570
+
571
+ const authorityOptions: AuthorityOptions = {
572
+ protocolMode: this.config.auth.protocolMode,
573
+ knownAuthorities: this.config.auth.knownAuthorities,
574
+ cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
575
+ authorityMetadata: this.config.auth.authorityMetadata,
576
+ azureRegionConfiguration,
577
+ skipAuthorityMetadataCache:
578
+ this.config.auth.skipAuthorityMetadataCache,
579
+ };
580
+
581
+ return await AuthorityFactory.createDiscoveredInstance(
582
+ authorityUrl,
583
+ this.config.system.networkClient,
584
+ this.storage,
585
+ authorityOptions,
586
+ this.logger
587
+ );
588
+ }
589
+
590
+ /**
591
+ * Clear the cache
592
+ */
593
+ clearCache(): void {
594
+ void this.storage.clear();
595
+ }
596
+ }