@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,283 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { ApiId, Constants } from "../utils/Constants.js";
7
+ import {
8
+ AuthenticationResult,
9
+ CommonDeviceCodeRequest,
10
+ AuthError,
11
+ ResponseMode,
12
+ OIDC_DEFAULT_SCOPES,
13
+ CodeChallengeMethodValues,
14
+ Constants as CommonConstants,
15
+ ServerError,
16
+ NativeRequest,
17
+ NativeSignOutRequest,
18
+ AccountInfo,
19
+ INativeBrokerPlugin,
20
+ ServerAuthorizationCodeResponse,
21
+ } from "@azure/msal-common";
22
+ import { Configuration } from "../config/Configuration.js";
23
+ import { ClientApplication } from "./ClientApplication.js";
24
+ import { IPublicClientApplication } from "./IPublicClientApplication.js";
25
+ import { DeviceCodeRequest } from "../request/DeviceCodeRequest.js";
26
+ import { AuthorizationUrlRequest } from "../request/AuthorizationUrlRequest.js";
27
+ import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest.js";
28
+ import { InteractiveRequest } from "../request/InteractiveRequest.js";
29
+ import { NodeAuthError } from "../error/NodeAuthError.js";
30
+ import { LoopbackClient } from "../network/LoopbackClient.js";
31
+ import { SilentFlowRequest } from "../request/SilentFlowRequest.js";
32
+ import { SignOutRequest } from "../request/SignOutRequest.js";
33
+ import { ILoopbackClient } from "../network/ILoopbackClient.js";
34
+ import { DeviceCodeClient } from "./DeviceCodeClient.js";
35
+
36
+ /**
37
+ * This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications
38
+ * are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.
39
+ * @public
40
+ */
41
+ export class PublicClientApplication
42
+ extends ClientApplication
43
+ implements IPublicClientApplication
44
+ {
45
+ private nativeBrokerPlugin?: INativeBrokerPlugin;
46
+ /**
47
+ * Important attributes in the Configuration object for auth are:
48
+ * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.
49
+ * - authority: the authority URL for your application.
50
+ *
51
+ * AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
52
+ * - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
53
+ * - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
54
+ * - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
55
+ * - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
56
+ *
57
+ * Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered
58
+ * its own authority. You will have to set the all of the knownAuthorities at the time of the client application
59
+ * construction.
60
+ *
61
+ * ADFS authorities are of the form https://\{instance\}/adfs.
62
+ */
63
+ constructor(configuration: Configuration) {
64
+ super(configuration);
65
+ if (this.config.broker.nativeBrokerPlugin) {
66
+ if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) {
67
+ this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin;
68
+ this.nativeBrokerPlugin.setLogger(
69
+ this.config.system.loggerOptions
70
+ );
71
+ } else {
72
+ this.logger.warning(
73
+ "NativeBroker implementation was provided but the broker is unavailable."
74
+ );
75
+ }
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Acquires a token from the authority using OAuth2.0 device code flow.
81
+ * This flow is designed for devices that do not have access to a browser or have input constraints.
82
+ * The authorization server issues a DeviceCode object with a verification code, an end-user code,
83
+ * and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be
84
+ * instructed to use another device to navigate to the verification URI to input credentials.
85
+ * Since the client cannot receive incoming requests, it polls the authorization server repeatedly
86
+ * until the end-user completes input of credentials.
87
+ */
88
+ public async acquireTokenByDeviceCode(
89
+ request: DeviceCodeRequest
90
+ ): Promise<AuthenticationResult | null> {
91
+ this.logger.info(
92
+ "acquireTokenByDeviceCode called",
93
+ request.correlationId
94
+ );
95
+ const validRequest: CommonDeviceCodeRequest = Object.assign(
96
+ request,
97
+ await this.initializeBaseRequest(request)
98
+ );
99
+ const serverTelemetryManager = this.initializeServerTelemetryManager(
100
+ ApiId.acquireTokenByDeviceCode,
101
+ validRequest.correlationId
102
+ );
103
+ try {
104
+ const deviceCodeConfig = await this.buildOauthClientConfiguration(
105
+ validRequest.authority,
106
+ validRequest.correlationId,
107
+ serverTelemetryManager,
108
+ undefined,
109
+ request.azureCloudOptions
110
+ );
111
+ const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig);
112
+ this.logger.verbose(
113
+ "Device code client created",
114
+ validRequest.correlationId
115
+ );
116
+ return deviceCodeClient.acquireToken(validRequest);
117
+ } catch (e) {
118
+ if (e instanceof AuthError) {
119
+ e.setCorrelationId(validRequest.correlationId);
120
+ }
121
+ serverTelemetryManager.cacheFailedRequest(e as AuthError);
122
+ throw e;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token.
128
+ */
129
+ async acquireTokenInteractive(
130
+ request: InteractiveRequest
131
+ ): Promise<AuthenticationResult> {
132
+ const correlationId =
133
+ request.correlationId || this.cryptoProvider.createNewGuid();
134
+ this.logger.trace("acquireTokenInteractive called", correlationId);
135
+ const {
136
+ openBrowser,
137
+ successTemplate,
138
+ errorTemplate,
139
+ windowHandle,
140
+ loopbackClient: customLoopbackClient,
141
+ ...remainingProperties
142
+ } = request;
143
+
144
+ if (this.nativeBrokerPlugin) {
145
+ const brokerRequest: NativeRequest = {
146
+ ...remainingProperties,
147
+ clientId: this.config.auth.clientId,
148
+ scopes: request.scopes || OIDC_DEFAULT_SCOPES,
149
+ redirectUri: `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}`,
150
+ authority: request.authority || this.config.auth.authority,
151
+ correlationId: correlationId,
152
+ extraParameters: {
153
+ ...remainingProperties.extraQueryParameters,
154
+ ...remainingProperties.tokenQueryParameters,
155
+ },
156
+ accountId: remainingProperties.account?.nativeAccountId,
157
+ };
158
+ return this.nativeBrokerPlugin.acquireTokenInteractive(
159
+ brokerRequest,
160
+ windowHandle
161
+ );
162
+ }
163
+
164
+ const { verifier, challenge } =
165
+ await this.cryptoProvider.generatePkceCodes();
166
+
167
+ const loopbackClient: ILoopbackClient =
168
+ customLoopbackClient || new LoopbackClient();
169
+
170
+ let authCodeListener: Promise<ServerAuthorizationCodeResponse>;
171
+ try {
172
+ authCodeListener = loopbackClient.listenForAuthCode(
173
+ successTemplate,
174
+ errorTemplate
175
+ );
176
+ const redirectUri = loopbackClient.getRedirectUri();
177
+
178
+ const validRequest: AuthorizationUrlRequest = {
179
+ ...remainingProperties,
180
+ correlationId: correlationId,
181
+ scopes: request.scopes || OIDC_DEFAULT_SCOPES,
182
+ redirectUri: redirectUri,
183
+ responseMode: ResponseMode.QUERY,
184
+ codeChallenge: challenge,
185
+ codeChallengeMethod: CodeChallengeMethodValues.S256,
186
+ };
187
+
188
+ const authCodeUrl = await this.getAuthCodeUrl(validRequest);
189
+ await openBrowser(authCodeUrl);
190
+ const authCodeResponse = await authCodeListener.finally(() => {
191
+ loopbackClient.closeServer();
192
+ });
193
+
194
+ if (authCodeResponse.error) {
195
+ throw new ServerError(
196
+ authCodeResponse.error,
197
+ authCodeResponse.error_description,
198
+ authCodeResponse.suberror
199
+ );
200
+ } else if (!authCodeResponse.code) {
201
+ throw NodeAuthError.createNoAuthCodeInResponseError();
202
+ }
203
+
204
+ const clientInfo = authCodeResponse.client_info;
205
+ const tokenRequest: AuthorizationCodeRequest = {
206
+ code: authCodeResponse.code,
207
+ codeVerifier: verifier,
208
+ clientInfo: clientInfo || CommonConstants.EMPTY_STRING,
209
+ ...validRequest,
210
+ };
211
+ return this.acquireTokenByCode(tokenRequest);
212
+ } catch (e) {
213
+ loopbackClient.closeServer();
214
+ throw e;
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker.
220
+ * @param request
221
+ * @returns
222
+ */
223
+ async acquireTokenSilent(
224
+ request: SilentFlowRequest
225
+ ): Promise<AuthenticationResult> {
226
+ const correlationId =
227
+ request.correlationId || this.cryptoProvider.createNewGuid();
228
+ this.logger.trace("acquireTokenSilent called", correlationId);
229
+
230
+ if (this.nativeBrokerPlugin) {
231
+ const brokerRequest: NativeRequest = {
232
+ ...request,
233
+ clientId: this.config.auth.clientId,
234
+ scopes: request.scopes || OIDC_DEFAULT_SCOPES,
235
+ redirectUri: `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}`,
236
+ authority: request.authority || this.config.auth.authority,
237
+ correlationId: correlationId,
238
+ extraParameters: request.tokenQueryParameters,
239
+ accountId: request.account.nativeAccountId,
240
+ forceRefresh: request.forceRefresh || false,
241
+ };
242
+ return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest);
243
+ }
244
+
245
+ return super.acquireTokenSilent(request);
246
+ }
247
+
248
+ /**
249
+ * Removes cache artifacts associated with the given account
250
+ * @param request
251
+ * @returns
252
+ */
253
+ async signOut(request: SignOutRequest): Promise<void> {
254
+ if (this.nativeBrokerPlugin && request.account.nativeAccountId) {
255
+ const signoutRequest: NativeSignOutRequest = {
256
+ clientId: this.config.auth.clientId,
257
+ accountId: request.account.nativeAccountId,
258
+ correlationId:
259
+ request.correlationId ||
260
+ this.cryptoProvider.createNewGuid(),
261
+ };
262
+ await this.nativeBrokerPlugin.signOut(signoutRequest);
263
+ }
264
+
265
+ await this.getTokenCache().removeAccount(request.account);
266
+ }
267
+
268
+ /**
269
+ * Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker.
270
+ * @returns
271
+ */
272
+ async getAllAccounts(): Promise<AccountInfo[]> {
273
+ if (this.nativeBrokerPlugin) {
274
+ const correlationId = this.cryptoProvider.createNewGuid();
275
+ return this.nativeBrokerPlugin.getAllAccounts(
276
+ this.config.auth.clientId,
277
+ correlationId
278
+ );
279
+ }
280
+
281
+ return this.getTokenCache().getAllAccounts();
282
+ }
283
+ }
@@ -0,0 +1,180 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import {
7
+ AuthenticationResult,
8
+ Authority,
9
+ BaseClient,
10
+ CcsCredentialType,
11
+ ClientConfiguration,
12
+ CommonUsernamePasswordRequest,
13
+ GrantType,
14
+ NetworkResponse,
15
+ RequestParameterBuilder,
16
+ RequestThumbprint,
17
+ ResponseHandler,
18
+ ServerAuthorizationTokenResponse,
19
+ StringUtils,
20
+ TimeUtils,
21
+ UrlString,
22
+ } from "@azure/msal-common";
23
+
24
+ /**
25
+ * Oauth2.0 Password grant client
26
+ * Note: We are only supporting public clients for password grant and for purely testing purposes
27
+ */
28
+ export class UsernamePasswordClient extends BaseClient {
29
+ constructor(configuration: ClientConfiguration) {
30
+ super(configuration);
31
+ }
32
+
33
+ /**
34
+ * API to acquire a token by passing the username and password to the service in exchage of credentials
35
+ * password_grant
36
+ * @param request
37
+ */
38
+ async acquireToken(
39
+ request: CommonUsernamePasswordRequest
40
+ ): Promise<AuthenticationResult | null> {
41
+ this.logger.info("in acquireToken call in username-password client");
42
+
43
+ const reqTimestamp = TimeUtils.nowSeconds();
44
+ const response = await this.executeTokenRequest(
45
+ this.authority,
46
+ request
47
+ );
48
+
49
+ const responseHandler = new ResponseHandler(
50
+ this.config.authOptions.clientId,
51
+ this.cacheManager,
52
+ this.cryptoUtils,
53
+ this.logger,
54
+ this.config.serializableCache,
55
+ this.config.persistencePlugin
56
+ );
57
+
58
+ // Validate response. This function throws a server error if an error is returned by the server.
59
+ responseHandler.validateTokenResponse(response.body);
60
+ const tokenResponse = responseHandler.handleServerTokenResponse(
61
+ response.body,
62
+ this.authority,
63
+ reqTimestamp,
64
+ request
65
+ );
66
+
67
+ return tokenResponse;
68
+ }
69
+
70
+ /**
71
+ * Executes POST request to token endpoint
72
+ * @param authority
73
+ * @param request
74
+ */
75
+ private async executeTokenRequest(
76
+ authority: Authority,
77
+ request: CommonUsernamePasswordRequest
78
+ ): Promise<NetworkResponse<ServerAuthorizationTokenResponse>> {
79
+ const queryParametersString = this.createTokenQueryParameters(request);
80
+ const endpoint = UrlString.appendQueryString(
81
+ authority.tokenEndpoint,
82
+ queryParametersString
83
+ );
84
+ const requestBody = this.createTokenRequestBody(request);
85
+ const headers: Record<string, string> = this.createTokenRequestHeaders({
86
+ credential: request.username,
87
+ type: CcsCredentialType.UPN,
88
+ });
89
+ const thumbprint: RequestThumbprint = {
90
+ clientId: this.config.authOptions.clientId,
91
+ authority: authority.canonicalAuthority,
92
+ scopes: request.scopes,
93
+ claims: request.claims,
94
+ authenticationScheme: request.authenticationScheme,
95
+ resourceRequestMethod: request.resourceRequestMethod,
96
+ resourceRequestUri: request.resourceRequestUri,
97
+ shrClaims: request.shrClaims,
98
+ sshKid: request.sshKid,
99
+ };
100
+
101
+ return this.executePostToTokenEndpoint(
102
+ endpoint,
103
+ requestBody,
104
+ headers,
105
+ thumbprint,
106
+ request.correlationId
107
+ );
108
+ }
109
+
110
+ /**
111
+ * Generates a map for all the params to be sent to the service
112
+ * @param request
113
+ */
114
+ private createTokenRequestBody(
115
+ request: CommonUsernamePasswordRequest
116
+ ): string {
117
+ const parameterBuilder = new RequestParameterBuilder();
118
+
119
+ parameterBuilder.addClientId(this.config.authOptions.clientId);
120
+ parameterBuilder.addUsername(request.username);
121
+ parameterBuilder.addPassword(request.password);
122
+
123
+ parameterBuilder.addScopes(request.scopes);
124
+
125
+ parameterBuilder.addResponseTypeForTokenAndIdToken();
126
+
127
+ parameterBuilder.addGrantType(GrantType.RESOURCE_OWNER_PASSWORD_GRANT);
128
+ parameterBuilder.addClientInfo();
129
+
130
+ parameterBuilder.addLibraryInfo(this.config.libraryInfo);
131
+ parameterBuilder.addApplicationTelemetry(
132
+ this.config.telemetry.application
133
+ );
134
+ parameterBuilder.addThrottling();
135
+
136
+ if (this.serverTelemetryManager) {
137
+ parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
138
+ }
139
+
140
+ const correlationId =
141
+ request.correlationId ||
142
+ this.config.cryptoInterface.createNewGuid();
143
+ parameterBuilder.addCorrelationId(correlationId);
144
+
145
+ if (this.config.clientCredentials.clientSecret) {
146
+ parameterBuilder.addClientSecret(
147
+ this.config.clientCredentials.clientSecret
148
+ );
149
+ }
150
+
151
+ if (this.config.clientCredentials.clientAssertion) {
152
+ const clientAssertion =
153
+ this.config.clientCredentials.clientAssertion;
154
+ parameterBuilder.addClientAssertion(clientAssertion.assertion);
155
+ parameterBuilder.addClientAssertionType(
156
+ clientAssertion.assertionType
157
+ );
158
+ }
159
+
160
+ if (
161
+ !StringUtils.isEmptyObj(request.claims) ||
162
+ (this.config.authOptions.clientCapabilities &&
163
+ this.config.authOptions.clientCapabilities.length > 0)
164
+ ) {
165
+ parameterBuilder.addClaims(
166
+ request.claims,
167
+ this.config.authOptions.clientCapabilities
168
+ );
169
+ }
170
+
171
+ if (
172
+ this.config.systemOptions.preventCorsPreflight &&
173
+ request.username
174
+ ) {
175
+ parameterBuilder.addCcsUpn(request.username);
176
+ }
177
+
178
+ return parameterBuilder.createQueryString();
179
+ }
180
+ }
@@ -0,0 +1,201 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import {
7
+ LoggerOptions,
8
+ INetworkModule,
9
+ LogLevel,
10
+ ProtocolMode,
11
+ ICachePlugin,
12
+ Constants,
13
+ AzureCloudInstance,
14
+ AzureCloudOptions,
15
+ ApplicationTelemetry,
16
+ INativeBrokerPlugin,
17
+ } from "@azure/msal-common";
18
+ import { HttpClient } from "../network/HttpClient.js";
19
+ import http from "http";
20
+ import https from "https";
21
+
22
+ /**
23
+ * - clientId - Client id of the application.
24
+ * - authority - Url of the authority. If no value is set, defaults to https://login.microsoftonline.com/common.
25
+ * - knownAuthorities - Needed for Azure B2C and ADFS. All authorities that will be used in the client application. Only the host of the authority should be passed in.
26
+ * - clientSecret - Secret string that the application uses when requesting a token. Only used in confidential client applications. Can be created in the Azure app registration portal.
27
+ * - clientAssertion - Assertion string that the application uses when requesting a token. Only used in confidential client applications. Assertion should be of type urn:ietf:params:oauth:client-assertion-type:jwt-bearer.
28
+ * - clientCertificate - Certificate that the application uses when requesting a token. Only used in confidential client applications. Requires hex encoded X.509 SHA-1 thumbprint of the certificiate, and the PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- )
29
+ * - protocolMode - Enum that represents the protocol that msal follows. Used for configuring proper endpoints.
30
+ * - skipAuthorityMetadataCache - A flag to choose whether to use or not use the local metadata cache during authority initialization. Defaults to false.
31
+ * @public
32
+ */
33
+ export type NodeAuthOptions = {
34
+ clientId: string;
35
+ authority?: string;
36
+ clientSecret?: string;
37
+ clientAssertion?: string;
38
+ clientCertificate?: {
39
+ thumbprint: string;
40
+ privateKey: string;
41
+ x5c?: string;
42
+ };
43
+ knownAuthorities?: Array<string>;
44
+ cloudDiscoveryMetadata?: string;
45
+ authorityMetadata?: string;
46
+ clientCapabilities?: Array<string>;
47
+ protocolMode?: ProtocolMode;
48
+ azureCloudOptions?: AzureCloudOptions;
49
+ skipAuthorityMetadataCache?: boolean;
50
+ };
51
+
52
+ /**
53
+ * Use this to configure the below cache configuration options:
54
+ *
55
+ * - cachePlugin - Plugin for reading and writing token cache to disk.
56
+ * @public
57
+ */
58
+ export type CacheOptions = {
59
+ cachePlugin?: ICachePlugin;
60
+ claimsBasedCachingEnabled?: boolean;
61
+ };
62
+
63
+ /**
64
+ * Use this to configure the below broker options:
65
+ * - nativeBrokerPlugin - Native broker implementation (should be imported from msal-node-extensions)
66
+ *
67
+ * Note: These options are only available for PublicClientApplications using the Authorization Code Flow
68
+ * @public
69
+ */
70
+ export type BrokerOptions = {
71
+ nativeBrokerPlugin?: INativeBrokerPlugin;
72
+ };
73
+
74
+ /**
75
+ * Type for configuring logger and http client options
76
+ *
77
+ * - logger - Used to initialize the Logger object; TODO: Expand on logger details or link to the documentation on logger
78
+ * - networkClient - Http client used for all http get and post calls. Defaults to using MSAL's default http client.
79
+ * @public
80
+ */
81
+ export type NodeSystemOptions = {
82
+ loggerOptions?: LoggerOptions;
83
+ networkClient?: INetworkModule;
84
+ proxyUrl?: string;
85
+ customAgentOptions?: http.AgentOptions | https.AgentOptions;
86
+ };
87
+
88
+ export type NodeTelemetryOptions = {
89
+ application?: ApplicationTelemetry;
90
+ };
91
+
92
+ /**
93
+ * Use the configuration object to configure MSAL and initialize the client application object
94
+ *
95
+ * - auth: this is where you configure auth elements like clientID, authority used for authenticating against the Microsoft Identity Platform
96
+ * - broker: this is where you configure broker options
97
+ * - cache: this is where you configure cache location
98
+ * - system: this is where you can configure the network client, logger
99
+ * - telemetry: this is where you can configure telemetry options
100
+ * @public
101
+ */
102
+ export type Configuration = {
103
+ auth: NodeAuthOptions;
104
+ broker?: BrokerOptions;
105
+ cache?: CacheOptions;
106
+ system?: NodeSystemOptions;
107
+ telemetry?: NodeTelemetryOptions;
108
+ };
109
+
110
+ const DEFAULT_AUTH_OPTIONS: Required<NodeAuthOptions> = {
111
+ clientId: Constants.EMPTY_STRING,
112
+ authority: Constants.DEFAULT_AUTHORITY,
113
+ clientSecret: Constants.EMPTY_STRING,
114
+ clientAssertion: Constants.EMPTY_STRING,
115
+ clientCertificate: {
116
+ thumbprint: Constants.EMPTY_STRING,
117
+ privateKey: Constants.EMPTY_STRING,
118
+ x5c: Constants.EMPTY_STRING,
119
+ },
120
+ knownAuthorities: [],
121
+ cloudDiscoveryMetadata: Constants.EMPTY_STRING,
122
+ authorityMetadata: Constants.EMPTY_STRING,
123
+ clientCapabilities: [],
124
+ protocolMode: ProtocolMode.AAD,
125
+ azureCloudOptions: {
126
+ azureCloudInstance: AzureCloudInstance.None,
127
+ tenant: Constants.EMPTY_STRING,
128
+ },
129
+ skipAuthorityMetadataCache: false,
130
+ };
131
+
132
+ const DEFAULT_CACHE_OPTIONS: CacheOptions = {
133
+ claimsBasedCachingEnabled: false,
134
+ };
135
+
136
+ const DEFAULT_LOGGER_OPTIONS: LoggerOptions = {
137
+ loggerCallback: (): void => {
138
+ // allow users to not set logger call back
139
+ },
140
+ piiLoggingEnabled: false,
141
+ logLevel: LogLevel.Info,
142
+ };
143
+
144
+ const DEFAULT_SYSTEM_OPTIONS: Required<NodeSystemOptions> = {
145
+ loggerOptions: DEFAULT_LOGGER_OPTIONS,
146
+ networkClient: new HttpClient(),
147
+ proxyUrl: Constants.EMPTY_STRING,
148
+ customAgentOptions: {} as http.AgentOptions | https.AgentOptions,
149
+ };
150
+
151
+ const DEFAULT_TELEMETRY_OPTIONS: Required<NodeTelemetryOptions> = {
152
+ application: {
153
+ appName: Constants.EMPTY_STRING,
154
+ appVersion: Constants.EMPTY_STRING,
155
+ },
156
+ };
157
+
158
+ /** @internal */
159
+ export type NodeConfiguration = {
160
+ auth: Required<NodeAuthOptions>;
161
+ broker: BrokerOptions;
162
+ cache: CacheOptions;
163
+ system: Required<NodeSystemOptions>;
164
+ telemetry: Required<NodeTelemetryOptions>;
165
+ };
166
+
167
+ /**
168
+ * Sets the default options when not explicitly configured from app developer
169
+ *
170
+ * @param auth - Authentication options
171
+ * @param cache - Cache options
172
+ * @param system - System options
173
+ * @param telemetry - Telemetry options
174
+ *
175
+ * @returns Configuration
176
+ * @internal
177
+ */
178
+ export function buildAppConfiguration({
179
+ auth,
180
+ broker,
181
+ cache,
182
+ system,
183
+ telemetry,
184
+ }: Configuration): NodeConfiguration {
185
+ const systemOptions: Required<NodeSystemOptions> = {
186
+ ...DEFAULT_SYSTEM_OPTIONS,
187
+ networkClient: new HttpClient(
188
+ system?.proxyUrl,
189
+ system?.customAgentOptions as http.AgentOptions | https.AgentOptions
190
+ ),
191
+ loggerOptions: system?.loggerOptions || DEFAULT_LOGGER_OPTIONS,
192
+ };
193
+
194
+ return {
195
+ auth: { ...DEFAULT_AUTH_OPTIONS, ...auth },
196
+ broker: { ...broker },
197
+ cache: { ...DEFAULT_CACHE_OPTIONS, ...cache },
198
+ system: { ...systemOptions, ...system },
199
+ telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },
200
+ };
201
+ }