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