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