@azure/msal-node 2.0.0-alpha.1 → 2.0.0-beta.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 (112) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +182 -182
  3. package/dist/cache/ITokenCache.d.ts +15 -15
  4. package/dist/cache/NodeStorage.d.ts +182 -182
  5. package/dist/cache/NodeStorage.esm.js +401 -401
  6. package/dist/cache/NodeStorage.js +401 -401
  7. package/dist/cache/TokenCache.d.ts +90 -90
  8. package/dist/cache/TokenCache.esm.js +269 -269
  9. package/dist/cache/TokenCache.js +269 -269
  10. package/dist/cache/distributed/DistributedCachePlugin.d.ts +10 -10
  11. package/dist/cache/distributed/DistributedCachePlugin.esm.js +26 -26
  12. package/dist/cache/distributed/DistributedCachePlugin.js +26 -26
  13. package/dist/cache/distributed/ICacheClient.d.ts +17 -17
  14. package/dist/cache/distributed/IPartitionManager.d.ts +28 -28
  15. package/dist/cache/serializer/Deserializer.d.ts +42 -42
  16. package/dist/cache/serializer/Deserializer.esm.js +175 -175
  17. package/dist/cache/serializer/Deserializer.js +175 -175
  18. package/dist/cache/serializer/Serializer.d.ts +39 -39
  19. package/dist/cache/serializer/Serializer.esm.js +134 -134
  20. package/dist/cache/serializer/Serializer.js +134 -134
  21. package/dist/cache/serializer/SerializerTypes.d.ts +101 -101
  22. package/dist/client/ClientApplication.d.ts +142 -142
  23. package/dist/client/ClientApplication.esm.js +327 -327
  24. package/dist/client/ClientApplication.js +327 -327
  25. package/dist/client/ClientAssertion.d.ts +46 -46
  26. package/dist/client/ClientAssertion.esm.js +116 -116
  27. package/dist/client/ClientAssertion.js +116 -116
  28. package/dist/client/ClientCredentialClient.d.ts +33 -33
  29. package/dist/client/ClientCredentialClient.esm.js +157 -157
  30. package/dist/client/ClientCredentialClient.js +157 -157
  31. package/dist/client/ConfidentialClientApplication.d.ts +58 -58
  32. package/dist/client/ConfidentialClientApplication.esm.js +163 -163
  33. package/dist/client/ConfidentialClientApplication.js +163 -163
  34. package/dist/client/DeviceCodeClient.d.ts +53 -53
  35. package/dist/client/DeviceCodeClient.esm.js +207 -207
  36. package/dist/client/DeviceCodeClient.js +207 -207
  37. package/dist/client/IConfidentialClientApplication.d.ts +39 -39
  38. package/dist/client/IPublicClientApplication.d.ts +42 -42
  39. package/dist/client/OnBehalfOfClient.d.ts +47 -47
  40. package/dist/client/OnBehalfOfClient.esm.js +204 -204
  41. package/dist/client/OnBehalfOfClient.js +204 -204
  42. package/dist/client/PublicClientApplication.d.ts +65 -65
  43. package/dist/client/PublicClientApplication.esm.js +175 -175
  44. package/dist/client/PublicClientApplication.js +175 -175
  45. package/dist/client/UsernamePasswordClient.d.ts +25 -25
  46. package/dist/client/UsernamePasswordClient.esm.js +102 -102
  47. package/dist/client/UsernamePasswordClient.js +102 -102
  48. package/dist/config/Configuration.d.ts +105 -105
  49. package/dist/config/Configuration.esm.js +70 -70
  50. package/dist/config/Configuration.js +70 -70
  51. package/dist/crypto/CryptoProvider.d.ts +52 -52
  52. package/dist/crypto/CryptoProvider.esm.js +75 -75
  53. package/dist/crypto/CryptoProvider.js +75 -75
  54. package/dist/crypto/GuidGenerator.d.ts +14 -14
  55. package/dist/crypto/GuidGenerator.esm.js +22 -22
  56. package/dist/crypto/GuidGenerator.js +22 -22
  57. package/dist/crypto/HashUtils.d.ts +8 -8
  58. package/dist/crypto/HashUtils.esm.js +13 -13
  59. package/dist/crypto/HashUtils.js +13 -13
  60. package/dist/crypto/PkceGenerator.d.ts +22 -22
  61. package/dist/crypto/PkceGenerator.esm.js +49 -49
  62. package/dist/crypto/PkceGenerator.js +49 -49
  63. package/dist/error/NodeAuthError.d.ts +65 -65
  64. package/dist/error/NodeAuthError.esm.js +85 -85
  65. package/dist/error/NodeAuthError.js +85 -85
  66. package/dist/index.d.ts +41 -41
  67. package/dist/index.esm.js +1 -1
  68. package/dist/index.js +1 -1
  69. package/dist/internals.d.ts +6 -6
  70. package/dist/internals.esm.js +4 -4
  71. package/dist/internals.js +4 -4
  72. package/dist/network/HttpClient.d.ts +25 -25
  73. package/dist/network/HttpClient.esm.js +276 -276
  74. package/dist/network/HttpClient.js +276 -276
  75. package/dist/network/ILoopbackClient.d.ts +10 -10
  76. package/dist/network/LoopbackClient.d.ts +21 -21
  77. package/dist/network/LoopbackClient.esm.js +84 -84
  78. package/dist/network/LoopbackClient.js +84 -84
  79. package/dist/packageMetadata.d.ts +2 -2
  80. package/dist/packageMetadata.d.ts.map +1 -1
  81. package/dist/packageMetadata.esm.js +4 -4
  82. package/dist/packageMetadata.js +4 -4
  83. package/dist/request/AuthorizationCodeRequest.d.ts +21 -21
  84. package/dist/request/AuthorizationUrlRequest.d.ts +33 -33
  85. package/dist/request/ClientCredentialRequest.d.ts +14 -15
  86. package/dist/request/ClientCredentialRequest.d.ts.map +1 -1
  87. package/dist/request/DeviceCodeRequest.d.ts +15 -15
  88. package/dist/request/InteractiveRequest.d.ts +22 -22
  89. package/dist/request/OnBehalfOfRequest.d.ts +14 -14
  90. package/dist/request/RefreshTokenRequest.d.ts +17 -17
  91. package/dist/request/SignOutRequest.d.ts +5 -5
  92. package/dist/request/SilentFlowRequest.d.ts +16 -16
  93. package/dist/request/UsernamePasswordRequest.d.ts +19 -19
  94. package/dist/utils/Constants.d.ts +96 -92
  95. package/dist/utils/Constants.d.ts.map +1 -1
  96. package/dist/utils/Constants.esm.js +89 -93
  97. package/dist/utils/Constants.esm.js.map +1 -1
  98. package/dist/utils/Constants.js +93 -93
  99. package/dist/utils/Constants.js.map +1 -1
  100. package/dist/utils/EncodingUtils.d.ts +26 -26
  101. package/dist/utils/EncodingUtils.esm.js +44 -44
  102. package/dist/utils/EncodingUtils.js +44 -44
  103. package/dist/utils/NetworkUtils.d.ts +5 -5
  104. package/dist/utils/NetworkUtils.esm.js +38 -38
  105. package/dist/utils/NetworkUtils.js +38 -38
  106. package/package.json +77 -73
  107. package/dist/msal-node.cjs.development.js +0 -2705
  108. package/dist/msal-node.cjs.development.js.map +0 -1
  109. package/dist/msal-node.cjs.production.min.js +0 -2
  110. package/dist/msal-node.cjs.production.min.js.map +0 -1
  111. package/dist/msal-node.esm.js +0 -2594
  112. package/dist/msal-node.esm.js.map +0 -1
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-node v2.0.0-alpha.1 2023-05-08 */
1
+ /*! @azure/msal-node v2.0.0-beta.0 2023-06-19 */
2
2
  'use strict';
3
3
  'use strict';
4
4
 
@@ -12,332 +12,332 @@ var packageMetadata = require('../packageMetadata.js');
12
12
  var NodeAuthError = require('../error/NodeAuthError.js');
13
13
  var UsernamePasswordClient = require('./UsernamePasswordClient.js');
14
14
 
15
- /*
16
- * Copyright (c) Microsoft Corporation. All rights reserved.
17
- * Licensed under the MIT License.
18
- */
19
- /**
20
- * Base abstract class for all ClientApplications - public and confidential
21
- * @public
22
- */
23
- class ClientApplication {
24
- /**
25
- * Constructor for the ClientApplication
26
- */
27
- constructor(configuration) {
28
- this.config = Configuration.buildAppConfiguration(configuration);
29
- this.cryptoProvider = new CryptoProvider.CryptoProvider();
30
- this.logger = new msalCommon.Logger(this.config.system.loggerOptions, packageMetadata.name, packageMetadata.version);
31
- this.storage = new NodeStorage.NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider);
32
- this.tokenCache = new TokenCache.TokenCache(this.storage, this.logger, this.config.cache.cachePlugin);
33
- }
34
- /**
35
- * Creates the URL of the authorization request, letting the user input credentials and consent to the
36
- * application. The URL targets the /authorize endpoint of the authority configured in the
37
- * application object.
38
- *
39
- * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
40
- * sent in the request and should contain an authorization code, which can then be used to acquire tokens via
41
- * `acquireTokenByCode(AuthorizationCodeRequest)`.
42
- */
43
- async getAuthCodeUrl(request) {
44
- this.logger.info("getAuthCodeUrl called", request.correlationId);
45
- const validRequest = {
46
- ...request,
47
- ...(await this.initializeBaseRequest(request)),
48
- responseMode: request.responseMode || msalCommon.ResponseMode.QUERY,
49
- authenticationScheme: msalCommon.AuthenticationScheme.BEARER,
50
- };
51
- const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, undefined, undefined, request.azureCloudOptions);
52
- const authorizationCodeClient = new msalCommon.AuthorizationCodeClient(authClientConfig);
53
- this.logger.verbose("Auth code client created", validRequest.correlationId);
54
- return authorizationCodeClient.getAuthCodeUrl(validRequest);
55
- }
56
- /**
57
- * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0
58
- * Authorization Code flow.
59
- *
60
- * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0
61
- * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and
62
- * AuthorizationCodeRequest are the same.
63
- */
64
- async acquireTokenByCode(request, authCodePayLoad) {
65
- this.logger.info("acquireTokenByCode called");
66
- if (request.state && authCodePayLoad) {
67
- this.logger.info("acquireTokenByCode - validating state");
68
- this.validateState(request.state, authCodePayLoad.state || "");
69
- // eslint-disable-next-line no-param-reassign
70
- authCodePayLoad = { ...authCodePayLoad, state: "" };
71
- }
72
- const validRequest = {
73
- ...request,
74
- ...(await this.initializeBaseRequest(request)),
75
- authenticationScheme: msalCommon.AuthenticationScheme.BEARER,
76
- };
77
- const serverTelemetryManager = this.initializeServerTelemetryManager(Constants.ApiId.acquireTokenByCode, validRequest.correlationId);
78
- try {
79
- const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
80
- const authorizationCodeClient = new msalCommon.AuthorizationCodeClient(authClientConfig);
81
- this.logger.verbose("Auth code client created", validRequest.correlationId);
82
- return authorizationCodeClient.acquireToken(validRequest, authCodePayLoad);
83
- }
84
- catch (e) {
85
- if (e instanceof msalCommon.AuthError) {
86
- e.setCorrelationId(validRequest.correlationId);
87
- }
88
- serverTelemetryManager.cacheFailedRequest(e);
89
- throw e;
90
- }
91
- }
92
- /**
93
- * Acquires a token by exchanging the refresh token provided for a new set of tokens.
94
- *
95
- * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is
96
- * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will
97
- * handle the caching and refreshing of tokens automatically.
98
- */
99
- async acquireTokenByRefreshToken(request) {
100
- this.logger.info("acquireTokenByRefreshToken called", request.correlationId);
101
- const validRequest = {
102
- ...request,
103
- ...(await this.initializeBaseRequest(request)),
104
- authenticationScheme: msalCommon.AuthenticationScheme.BEARER,
105
- };
106
- const serverTelemetryManager = this.initializeServerTelemetryManager(Constants.ApiId.acquireTokenByRefreshToken, validRequest.correlationId);
107
- try {
108
- const refreshTokenClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
109
- const refreshTokenClient = new msalCommon.RefreshTokenClient(refreshTokenClientConfig);
110
- this.logger.verbose("Refresh token client created", validRequest.correlationId);
111
- return refreshTokenClient.acquireToken(validRequest);
112
- }
113
- catch (e) {
114
- if (e instanceof msalCommon.AuthError) {
115
- e.setCorrelationId(validRequest.correlationId);
116
- }
117
- serverTelemetryManager.cacheFailedRequest(e);
118
- throw e;
119
- }
120
- }
121
- /**
122
- * Acquires a token silently when a user specifies the account the token is requested for.
123
- *
124
- * This API expects the user to provide an account object and looks into the cache to retrieve the token if present.
125
- * There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token.
126
- * In case the refresh_token is expired or not found, an error is thrown
127
- * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).
128
- */
129
- async acquireTokenSilent(request) {
130
- const validRequest = {
131
- ...request,
132
- ...(await this.initializeBaseRequest(request)),
133
- forceRefresh: request.forceRefresh || false,
134
- };
135
- const serverTelemetryManager = this.initializeServerTelemetryManager(Constants.ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);
136
- try {
137
- const silentFlowClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
138
- const silentFlowClient = new msalCommon.SilentFlowClient(silentFlowClientConfig);
139
- this.logger.verbose("Silent flow client created", validRequest.correlationId);
140
- return silentFlowClient.acquireToken(validRequest);
141
- }
142
- catch (e) {
143
- if (e instanceof msalCommon.AuthError) {
144
- e.setCorrelationId(validRequest.correlationId);
145
- }
146
- serverTelemetryManager.cacheFailedRequest(e);
147
- throw e;
148
- }
149
- }
150
- /**
151
- * Acquires tokens with password grant by exchanging client applications username and password for credentials
152
- *
153
- * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.
154
- * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4
155
- * Microsoft's documentation and recommendations are at:
156
- * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword
157
- *
158
- * @param request - UsenamePasswordRequest
159
- */
160
- async acquireTokenByUsernamePassword(request) {
161
- this.logger.info("acquireTokenByUsernamePassword called", request.correlationId);
162
- const validRequest = {
163
- ...request,
164
- ...(await this.initializeBaseRequest(request)),
165
- };
166
- const serverTelemetryManager = this.initializeServerTelemetryManager(Constants.ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);
167
- try {
168
- const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
169
- const usernamePasswordClient = new UsernamePasswordClient.UsernamePasswordClient(usernamePasswordClientConfig);
170
- this.logger.verbose("Username password client created", validRequest.correlationId);
171
- return usernamePasswordClient.acquireToken(validRequest);
172
- }
173
- catch (e) {
174
- if (e instanceof msalCommon.AuthError) {
175
- e.setCorrelationId(validRequest.correlationId);
176
- }
177
- serverTelemetryManager.cacheFailedRequest(e);
178
- throw e;
179
- }
180
- }
181
- /**
182
- * Gets the token cache for the application.
183
- */
184
- getTokenCache() {
185
- this.logger.info("getTokenCache called");
186
- return this.tokenCache;
187
- }
188
- /**
189
- * Validates OIDC state by comparing the user cached state with the state received from the server.
190
- *
191
- * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against
192
- * CSRF attacks.
193
- * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.
194
- * @param state
195
- * @param cachedState
196
- */
197
- validateState(state, cachedState) {
198
- if (!state) {
199
- throw NodeAuthError.NodeAuthError.createStateNotFoundError();
200
- }
201
- if (state !== cachedState) {
202
- throw msalCommon.ClientAuthError.createStateMismatchError();
203
- }
204
- }
205
- /**
206
- * Returns the logger instance
207
- */
208
- getLogger() {
209
- return this.logger;
210
- }
211
- /**
212
- * Replaces the default logger set in configurations with new Logger with new configurations
213
- * @param logger - Logger instance
214
- */
215
- setLogger(logger) {
216
- this.logger = logger;
217
- }
218
- /**
219
- * Builds the common configuration to be passed to the common component based on the platform configurarion
220
- * @param authority - user passed authority in configuration
221
- * @param serverTelemetryManager - initializes servertelemetry if passed
222
- */
223
- async buildOauthClientConfiguration(authority, requestCorrelationId, serverTelemetryManager, azureRegionConfiguration, azureCloudOptions) {
224
- this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId);
225
- // precedence - azureCloudInstance + tenant >> authority and request >> config
226
- const userAzureCloudOptions = azureCloudOptions
227
- ? azureCloudOptions
228
- : this.config.auth.azureCloudOptions;
229
- // using null assertion operator as we ensure that all config values have default values in buildConfiguration()
230
- this.logger.verbose(`building oauth client configuration with the authority: ${authority}`, requestCorrelationId);
231
- const discoveredAuthority = await this.createAuthority(authority, azureRegionConfiguration, requestCorrelationId, userAzureCloudOptions);
232
- serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);
233
- const clientConfiguration = {
234
- authOptions: {
235
- clientId: this.config.auth.clientId,
236
- authority: discoveredAuthority,
237
- clientCapabilities: this.config.auth.clientCapabilities,
238
- },
239
- loggerOptions: {
240
- logLevel: this.config.system.loggerOptions.logLevel,
241
- loggerCallback: this.config.system.loggerOptions.loggerCallback,
242
- piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled,
243
- correlationId: requestCorrelationId,
244
- },
245
- cryptoInterface: this.cryptoProvider,
246
- networkInterface: this.config.system.networkClient,
247
- storageInterface: this.storage,
248
- serverTelemetryManager: serverTelemetryManager,
249
- clientCredentials: {
250
- clientSecret: this.clientSecret,
251
- clientAssertion: this.clientAssertion
252
- ? this.getClientAssertion(discoveredAuthority)
253
- : undefined,
254
- },
255
- libraryInfo: {
256
- sku: Constants.Constants.MSAL_SKU,
257
- version: packageMetadata.version,
258
- cpu: process.arch || msalCommon.Constants.EMPTY_STRING,
259
- os: process.platform || msalCommon.Constants.EMPTY_STRING,
260
- },
261
- telemetry: this.config.telemetry,
262
- persistencePlugin: this.config.cache.cachePlugin,
263
- serializableCache: this.tokenCache,
264
- };
265
- return clientConfiguration;
266
- }
267
- getClientAssertion(authority) {
268
- return {
269
- assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),
270
- assertionType: Constants.Constants.JWT_BEARER_ASSERTION_TYPE,
271
- };
272
- }
273
- /**
274
- * Generates a request with the default scopes & generates a correlationId.
275
- * @param authRequest - BaseAuthRequest for initialization
276
- */
277
- async initializeBaseRequest(authRequest) {
278
- this.logger.verbose("initializeRequestScopes called", authRequest.correlationId);
279
- // Default authenticationScheme to Bearer, log that POP isn't supported yet
280
- if (authRequest.authenticationScheme &&
281
- authRequest.authenticationScheme === msalCommon.AuthenticationScheme.POP) {
282
- this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", authRequest.correlationId);
283
- }
284
- authRequest.authenticationScheme = msalCommon.AuthenticationScheme.BEARER;
285
- // Set requested claims hash if claims were requested
286
- if (authRequest.claims && !msalCommon.StringUtils.isEmpty(authRequest.claims)) {
287
- authRequest.requestedClaimsHash =
288
- await this.cryptoProvider.hashString(authRequest.claims);
289
- }
290
- return {
291
- ...authRequest,
292
- scopes: [
293
- ...((authRequest && authRequest.scopes) || []),
294
- ...msalCommon.OIDC_DEFAULT_SCOPES,
295
- ],
296
- correlationId: (authRequest && authRequest.correlationId) ||
297
- this.cryptoProvider.createNewGuid(),
298
- authority: authRequest.authority || this.config.auth.authority,
299
- };
300
- }
301
- /**
302
- * Initializes the server telemetry payload
303
- * @param apiId - Id for a specific request
304
- * @param correlationId - GUID
305
- * @param forceRefresh - boolean to indicate network call
306
- */
307
- initializeServerTelemetryManager(apiId, correlationId, forceRefresh) {
308
- const telemetryPayload = {
309
- clientId: this.config.auth.clientId,
310
- correlationId: correlationId,
311
- apiId: apiId,
312
- forceRefresh: forceRefresh || false,
313
- };
314
- return new msalCommon.ServerTelemetryManager(telemetryPayload, this.storage);
315
- }
316
- /**
317
- * Create authority instance. If authority not passed in request, default to authority set on the application
318
- * object. If no authority set in application object, then default to common authority.
319
- * @param authorityString - authority from user configuration
320
- */
321
- async createAuthority(authorityString, azureRegionConfiguration, requestCorrelationId, azureCloudOptions) {
322
- this.logger.verbose("createAuthority called", requestCorrelationId);
323
- // build authority string based on auth params - azureCloudInstance is prioritized if provided
324
- const authorityUrl = msalCommon.Authority.generateAuthority(authorityString, azureCloudOptions);
325
- const authorityOptions = {
326
- protocolMode: this.config.auth.protocolMode,
327
- knownAuthorities: this.config.auth.knownAuthorities,
328
- cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
329
- authorityMetadata: this.config.auth.authorityMetadata,
330
- azureRegionConfiguration,
331
- skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache,
332
- };
333
- return await msalCommon.AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger);
334
- }
335
- /**
336
- * Clear the cache
337
- */
338
- clearCache() {
339
- this.storage.clear();
340
- }
15
+ /*
16
+ * Copyright (c) Microsoft Corporation. All rights reserved.
17
+ * Licensed under the MIT License.
18
+ */
19
+ /**
20
+ * Base abstract class for all ClientApplications - public and confidential
21
+ * @public
22
+ */
23
+ class ClientApplication {
24
+ /**
25
+ * Constructor for the ClientApplication
26
+ */
27
+ constructor(configuration) {
28
+ this.config = Configuration.buildAppConfiguration(configuration);
29
+ this.cryptoProvider = new CryptoProvider.CryptoProvider();
30
+ this.logger = new msalCommon.Logger(this.config.system.loggerOptions, packageMetadata.name, packageMetadata.version);
31
+ this.storage = new NodeStorage.NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider);
32
+ this.tokenCache = new TokenCache.TokenCache(this.storage, this.logger, this.config.cache.cachePlugin);
33
+ }
34
+ /**
35
+ * Creates the URL of the authorization request, letting the user input credentials and consent to the
36
+ * application. The URL targets the /authorize endpoint of the authority configured in the
37
+ * application object.
38
+ *
39
+ * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
40
+ * sent in the request and should contain an authorization code, which can then be used to acquire tokens via
41
+ * `acquireTokenByCode(AuthorizationCodeRequest)`.
42
+ */
43
+ async getAuthCodeUrl(request) {
44
+ this.logger.info("getAuthCodeUrl called", request.correlationId);
45
+ const validRequest = {
46
+ ...request,
47
+ ...(await this.initializeBaseRequest(request)),
48
+ responseMode: request.responseMode || msalCommon.ResponseMode.QUERY,
49
+ authenticationScheme: msalCommon.AuthenticationScheme.BEARER,
50
+ };
51
+ const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, undefined, undefined, request.azureCloudOptions);
52
+ const authorizationCodeClient = new msalCommon.AuthorizationCodeClient(authClientConfig);
53
+ this.logger.verbose("Auth code client created", validRequest.correlationId);
54
+ return authorizationCodeClient.getAuthCodeUrl(validRequest);
55
+ }
56
+ /**
57
+ * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0
58
+ * Authorization Code flow.
59
+ *
60
+ * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0
61
+ * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and
62
+ * AuthorizationCodeRequest are the same.
63
+ */
64
+ async acquireTokenByCode(request, authCodePayLoad) {
65
+ this.logger.info("acquireTokenByCode called");
66
+ if (request.state && authCodePayLoad) {
67
+ this.logger.info("acquireTokenByCode - validating state");
68
+ this.validateState(request.state, authCodePayLoad.state || "");
69
+ // eslint-disable-next-line no-param-reassign
70
+ authCodePayLoad = { ...authCodePayLoad, state: "" };
71
+ }
72
+ const validRequest = {
73
+ ...request,
74
+ ...(await this.initializeBaseRequest(request)),
75
+ authenticationScheme: msalCommon.AuthenticationScheme.BEARER,
76
+ };
77
+ const serverTelemetryManager = this.initializeServerTelemetryManager(Constants.ApiId.acquireTokenByCode, validRequest.correlationId);
78
+ try {
79
+ const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
80
+ const authorizationCodeClient = new msalCommon.AuthorizationCodeClient(authClientConfig);
81
+ this.logger.verbose("Auth code client created", validRequest.correlationId);
82
+ return authorizationCodeClient.acquireToken(validRequest, authCodePayLoad);
83
+ }
84
+ catch (e) {
85
+ if (e instanceof msalCommon.AuthError) {
86
+ e.setCorrelationId(validRequest.correlationId);
87
+ }
88
+ serverTelemetryManager.cacheFailedRequest(e);
89
+ throw e;
90
+ }
91
+ }
92
+ /**
93
+ * Acquires a token by exchanging the refresh token provided for a new set of tokens.
94
+ *
95
+ * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is
96
+ * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will
97
+ * handle the caching and refreshing of tokens automatically.
98
+ */
99
+ async acquireTokenByRefreshToken(request) {
100
+ this.logger.info("acquireTokenByRefreshToken called", request.correlationId);
101
+ const validRequest = {
102
+ ...request,
103
+ ...(await this.initializeBaseRequest(request)),
104
+ authenticationScheme: msalCommon.AuthenticationScheme.BEARER,
105
+ };
106
+ const serverTelemetryManager = this.initializeServerTelemetryManager(Constants.ApiId.acquireTokenByRefreshToken, validRequest.correlationId);
107
+ try {
108
+ const refreshTokenClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
109
+ const refreshTokenClient = new msalCommon.RefreshTokenClient(refreshTokenClientConfig);
110
+ this.logger.verbose("Refresh token client created", validRequest.correlationId);
111
+ return refreshTokenClient.acquireToken(validRequest);
112
+ }
113
+ catch (e) {
114
+ if (e instanceof msalCommon.AuthError) {
115
+ e.setCorrelationId(validRequest.correlationId);
116
+ }
117
+ serverTelemetryManager.cacheFailedRequest(e);
118
+ throw e;
119
+ }
120
+ }
121
+ /**
122
+ * Acquires a token silently when a user specifies the account the token is requested for.
123
+ *
124
+ * This API expects the user to provide an account object and looks into the cache to retrieve the token if present.
125
+ * There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token.
126
+ * In case the refresh_token is expired or not found, an error is thrown
127
+ * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).
128
+ */
129
+ async acquireTokenSilent(request) {
130
+ const validRequest = {
131
+ ...request,
132
+ ...(await this.initializeBaseRequest(request)),
133
+ forceRefresh: request.forceRefresh || false,
134
+ };
135
+ const serverTelemetryManager = this.initializeServerTelemetryManager(Constants.ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);
136
+ try {
137
+ const silentFlowClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
138
+ const silentFlowClient = new msalCommon.SilentFlowClient(silentFlowClientConfig);
139
+ this.logger.verbose("Silent flow client created", validRequest.correlationId);
140
+ return silentFlowClient.acquireToken(validRequest);
141
+ }
142
+ catch (e) {
143
+ if (e instanceof msalCommon.AuthError) {
144
+ e.setCorrelationId(validRequest.correlationId);
145
+ }
146
+ serverTelemetryManager.cacheFailedRequest(e);
147
+ throw e;
148
+ }
149
+ }
150
+ /**
151
+ * Acquires tokens with password grant by exchanging client applications username and password for credentials
152
+ *
153
+ * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.
154
+ * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4
155
+ * Microsoft's documentation and recommendations are at:
156
+ * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword
157
+ *
158
+ * @param request - UsenamePasswordRequest
159
+ */
160
+ async acquireTokenByUsernamePassword(request) {
161
+ this.logger.info("acquireTokenByUsernamePassword called", request.correlationId);
162
+ const validRequest = {
163
+ ...request,
164
+ ...(await this.initializeBaseRequest(request)),
165
+ };
166
+ const serverTelemetryManager = this.initializeServerTelemetryManager(Constants.ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);
167
+ try {
168
+ const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
169
+ const usernamePasswordClient = new UsernamePasswordClient.UsernamePasswordClient(usernamePasswordClientConfig);
170
+ this.logger.verbose("Username password client created", validRequest.correlationId);
171
+ return usernamePasswordClient.acquireToken(validRequest);
172
+ }
173
+ catch (e) {
174
+ if (e instanceof msalCommon.AuthError) {
175
+ e.setCorrelationId(validRequest.correlationId);
176
+ }
177
+ serverTelemetryManager.cacheFailedRequest(e);
178
+ throw e;
179
+ }
180
+ }
181
+ /**
182
+ * Gets the token cache for the application.
183
+ */
184
+ getTokenCache() {
185
+ this.logger.info("getTokenCache called");
186
+ return this.tokenCache;
187
+ }
188
+ /**
189
+ * Validates OIDC state by comparing the user cached state with the state received from the server.
190
+ *
191
+ * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against
192
+ * CSRF attacks.
193
+ * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.
194
+ * @param state
195
+ * @param cachedState
196
+ */
197
+ validateState(state, cachedState) {
198
+ if (!state) {
199
+ throw NodeAuthError.NodeAuthError.createStateNotFoundError();
200
+ }
201
+ if (state !== cachedState) {
202
+ throw msalCommon.ClientAuthError.createStateMismatchError();
203
+ }
204
+ }
205
+ /**
206
+ * Returns the logger instance
207
+ */
208
+ getLogger() {
209
+ return this.logger;
210
+ }
211
+ /**
212
+ * Replaces the default logger set in configurations with new Logger with new configurations
213
+ * @param logger - Logger instance
214
+ */
215
+ setLogger(logger) {
216
+ this.logger = logger;
217
+ }
218
+ /**
219
+ * Builds the common configuration to be passed to the common component based on the platform configurarion
220
+ * @param authority - user passed authority in configuration
221
+ * @param serverTelemetryManager - initializes servertelemetry if passed
222
+ */
223
+ async buildOauthClientConfiguration(authority, requestCorrelationId, serverTelemetryManager, azureRegionConfiguration, azureCloudOptions) {
224
+ this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId);
225
+ // precedence - azureCloudInstance + tenant >> authority and request >> config
226
+ const userAzureCloudOptions = azureCloudOptions
227
+ ? azureCloudOptions
228
+ : this.config.auth.azureCloudOptions;
229
+ // using null assertion operator as we ensure that all config values have default values in buildConfiguration()
230
+ this.logger.verbose(`building oauth client configuration with the authority: ${authority}`, requestCorrelationId);
231
+ const discoveredAuthority = await this.createAuthority(authority, azureRegionConfiguration, requestCorrelationId, userAzureCloudOptions);
232
+ serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);
233
+ const clientConfiguration = {
234
+ authOptions: {
235
+ clientId: this.config.auth.clientId,
236
+ authority: discoveredAuthority,
237
+ clientCapabilities: this.config.auth.clientCapabilities,
238
+ },
239
+ loggerOptions: {
240
+ logLevel: this.config.system.loggerOptions.logLevel,
241
+ loggerCallback: this.config.system.loggerOptions.loggerCallback,
242
+ piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled,
243
+ correlationId: requestCorrelationId,
244
+ },
245
+ cryptoInterface: this.cryptoProvider,
246
+ networkInterface: this.config.system.networkClient,
247
+ storageInterface: this.storage,
248
+ serverTelemetryManager: serverTelemetryManager,
249
+ clientCredentials: {
250
+ clientSecret: this.clientSecret,
251
+ clientAssertion: this.clientAssertion
252
+ ? this.getClientAssertion(discoveredAuthority)
253
+ : undefined,
254
+ },
255
+ libraryInfo: {
256
+ sku: Constants.Constants.MSAL_SKU,
257
+ version: packageMetadata.version,
258
+ cpu: process.arch || msalCommon.Constants.EMPTY_STRING,
259
+ os: process.platform || msalCommon.Constants.EMPTY_STRING,
260
+ },
261
+ telemetry: this.config.telemetry,
262
+ persistencePlugin: this.config.cache.cachePlugin,
263
+ serializableCache: this.tokenCache,
264
+ };
265
+ return clientConfiguration;
266
+ }
267
+ getClientAssertion(authority) {
268
+ return {
269
+ assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),
270
+ assertionType: Constants.Constants.JWT_BEARER_ASSERTION_TYPE,
271
+ };
272
+ }
273
+ /**
274
+ * Generates a request with the default scopes & generates a correlationId.
275
+ * @param authRequest - BaseAuthRequest for initialization
276
+ */
277
+ async initializeBaseRequest(authRequest) {
278
+ this.logger.verbose("initializeRequestScopes called", authRequest.correlationId);
279
+ // Default authenticationScheme to Bearer, log that POP isn't supported yet
280
+ if (authRequest.authenticationScheme &&
281
+ authRequest.authenticationScheme === msalCommon.AuthenticationScheme.POP) {
282
+ this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", authRequest.correlationId);
283
+ }
284
+ authRequest.authenticationScheme = msalCommon.AuthenticationScheme.BEARER;
285
+ // Set requested claims hash if claims were requested
286
+ if (authRequest.claims && !msalCommon.StringUtils.isEmpty(authRequest.claims)) {
287
+ authRequest.requestedClaimsHash =
288
+ await this.cryptoProvider.hashString(authRequest.claims);
289
+ }
290
+ return {
291
+ ...authRequest,
292
+ scopes: [
293
+ ...((authRequest && authRequest.scopes) || []),
294
+ ...msalCommon.OIDC_DEFAULT_SCOPES,
295
+ ],
296
+ correlationId: (authRequest && authRequest.correlationId) ||
297
+ this.cryptoProvider.createNewGuid(),
298
+ authority: authRequest.authority || this.config.auth.authority,
299
+ };
300
+ }
301
+ /**
302
+ * Initializes the server telemetry payload
303
+ * @param apiId - Id for a specific request
304
+ * @param correlationId - GUID
305
+ * @param forceRefresh - boolean to indicate network call
306
+ */
307
+ initializeServerTelemetryManager(apiId, correlationId, forceRefresh) {
308
+ const telemetryPayload = {
309
+ clientId: this.config.auth.clientId,
310
+ correlationId: correlationId,
311
+ apiId: apiId,
312
+ forceRefresh: forceRefresh || false,
313
+ };
314
+ return new msalCommon.ServerTelemetryManager(telemetryPayload, this.storage);
315
+ }
316
+ /**
317
+ * Create authority instance. If authority not passed in request, default to authority set on the application
318
+ * object. If no authority set in application object, then default to common authority.
319
+ * @param authorityString - authority from user configuration
320
+ */
321
+ async createAuthority(authorityString, azureRegionConfiguration, requestCorrelationId, azureCloudOptions) {
322
+ this.logger.verbose("createAuthority called", requestCorrelationId);
323
+ // build authority string based on auth params - azureCloudInstance is prioritized if provided
324
+ const authorityUrl = msalCommon.Authority.generateAuthority(authorityString, azureCloudOptions);
325
+ const authorityOptions = {
326
+ protocolMode: this.config.auth.protocolMode,
327
+ knownAuthorities: this.config.auth.knownAuthorities,
328
+ cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
329
+ authorityMetadata: this.config.auth.authorityMetadata,
330
+ azureRegionConfiguration,
331
+ skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache,
332
+ };
333
+ return await msalCommon.AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger);
334
+ }
335
+ /**
336
+ * Clear the cache
337
+ */
338
+ clearCache() {
339
+ this.storage.clear();
340
+ }
341
341
  }
342
342
 
343
343
  exports.ClientApplication = ClientApplication;