@azure/msal-node 2.0.2 → 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 (191) 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 +1 -1
  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 +1 -1
  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 +1 -1
  82. package/dist/config/Configuration.cjs.map +1 -1
  83. package/dist/config/Configuration.mjs +1 -1
  84. package/dist/config/Configuration.mjs.map +1 -1
  85. package/dist/crypto/CryptoProvider.cjs +1 -1
  86. package/dist/crypto/CryptoProvider.cjs.map +1 -1
  87. package/dist/crypto/CryptoProvider.mjs +1 -1
  88. package/dist/crypto/CryptoProvider.mjs.map +1 -1
  89. package/dist/crypto/GuidGenerator.cjs +1 -1
  90. package/dist/crypto/GuidGenerator.cjs.map +1 -1
  91. package/dist/crypto/GuidGenerator.mjs +1 -1
  92. package/dist/crypto/GuidGenerator.mjs.map +1 -1
  93. package/dist/crypto/HashUtils.cjs +1 -1
  94. package/dist/crypto/HashUtils.cjs.map +1 -1
  95. package/dist/crypto/HashUtils.mjs +1 -1
  96. package/dist/crypto/HashUtils.mjs.map +1 -1
  97. package/dist/crypto/PkceGenerator.cjs +1 -1
  98. package/dist/crypto/PkceGenerator.cjs.map +1 -1
  99. package/dist/crypto/PkceGenerator.mjs +1 -1
  100. package/dist/crypto/PkceGenerator.mjs.map +1 -1
  101. package/dist/error/NodeAuthError.cjs +1 -1
  102. package/dist/error/NodeAuthError.cjs.map +1 -1
  103. package/dist/error/NodeAuthError.mjs +1 -1
  104. package/dist/error/NodeAuthError.mjs.map +1 -1
  105. package/dist/index.cjs +1 -1
  106. package/dist/index.d.ts +32 -32
  107. package/dist/index.d.ts.map +1 -1
  108. package/dist/index.mjs +1 -1
  109. package/dist/internals.cjs +1 -1
  110. package/dist/internals.cjs.map +1 -1
  111. package/dist/internals.d.ts +2 -2
  112. package/dist/internals.d.ts.map +1 -1
  113. package/dist/internals.mjs +1 -1
  114. package/dist/internals.mjs.map +1 -1
  115. package/dist/network/HttpClient.cjs +10 -9
  116. package/dist/network/HttpClient.cjs.map +1 -1
  117. package/dist/network/HttpClient.d.ts.map +1 -1
  118. package/dist/network/HttpClient.mjs +3 -2
  119. package/dist/network/HttpClient.mjs.map +1 -1
  120. package/dist/network/LoopbackClient.cjs +2 -2
  121. package/dist/network/LoopbackClient.cjs.map +1 -1
  122. package/dist/network/LoopbackClient.d.ts +1 -1
  123. package/dist/network/LoopbackClient.d.ts.map +1 -1
  124. package/dist/network/LoopbackClient.mjs +3 -3
  125. package/dist/network/LoopbackClient.mjs.map +1 -1
  126. package/dist/packageMetadata.cjs +2 -2
  127. package/dist/packageMetadata.cjs.map +1 -1
  128. package/dist/packageMetadata.d.ts +1 -1
  129. package/dist/packageMetadata.mjs +2 -2
  130. package/dist/packageMetadata.mjs.map +1 -1
  131. package/dist/request/InteractiveRequest.d.ts +2 -2
  132. package/dist/request/InteractiveRequest.d.ts.map +1 -1
  133. package/dist/utils/Constants.cjs +1 -11
  134. package/dist/utils/Constants.cjs.map +1 -1
  135. package/dist/utils/Constants.d.ts +0 -10
  136. package/dist/utils/Constants.d.ts.map +1 -1
  137. package/dist/utils/Constants.mjs +2 -11
  138. package/dist/utils/Constants.mjs.map +1 -1
  139. package/dist/utils/EncodingUtils.cjs +1 -1
  140. package/dist/utils/EncodingUtils.cjs.map +1 -1
  141. package/dist/utils/EncodingUtils.mjs +1 -1
  142. package/dist/utils/EncodingUtils.mjs.map +1 -1
  143. package/dist/utils/NetworkUtils.cjs +1 -1
  144. package/dist/utils/NetworkUtils.cjs.map +1 -1
  145. package/dist/utils/NetworkUtils.mjs +1 -1
  146. package/dist/utils/NetworkUtils.mjs.map +1 -1
  147. package/package.json +8 -5
  148. package/src/cache/ITokenCache.ts +24 -0
  149. package/src/cache/NodeStorage.ts +533 -0
  150. package/src/cache/TokenCache.ts +358 -0
  151. package/src/cache/distributed/DistributedCachePlugin.ts +56 -0
  152. package/src/cache/distributed/ICacheClient.ts +23 -0
  153. package/src/cache/distributed/IPartitionManager.ts +35 -0
  154. package/src/cache/serializer/Deserializer.ts +218 -0
  155. package/src/cache/serializer/Serializer.ts +173 -0
  156. package/src/cache/serializer/SerializerTypes.ts +121 -0
  157. package/src/client/ClientApplication.ts +595 -0
  158. package/src/client/ClientAssertion.ts +160 -0
  159. package/src/client/ClientCredentialClient.ts +348 -0
  160. package/src/client/ConfidentialClientApplication.ts +261 -0
  161. package/src/client/DeviceCodeClient.ts +360 -0
  162. package/src/client/IConfidentialClientApplication.ts +72 -0
  163. package/src/client/IPublicClientApplication.ts +72 -0
  164. package/src/client/OnBehalfOfClient.ts +361 -0
  165. package/src/client/PublicClientApplication.ts +283 -0
  166. package/src/client/UsernamePasswordClient.ts +180 -0
  167. package/src/config/Configuration.ts +201 -0
  168. package/src/crypto/CryptoProvider.ts +98 -0
  169. package/src/crypto/GuidGenerator.ts +28 -0
  170. package/src/crypto/HashUtils.ts +17 -0
  171. package/src/crypto/PkceGenerator.ts +63 -0
  172. package/src/error/NodeAuthError.ts +117 -0
  173. package/src/index.ts +121 -0
  174. package/src/internals.ts +12 -0
  175. package/src/network/HttpClient.ts +425 -0
  176. package/src/network/ILoopbackClient.ts +19 -0
  177. package/src/network/LoopbackClient.ts +126 -0
  178. package/src/packageMetadata.ts +3 -0
  179. package/src/request/AuthorizationCodeRequest.ts +39 -0
  180. package/src/request/AuthorizationUrlRequest.ts +50 -0
  181. package/src/request/ClientCredentialRequest.ts +29 -0
  182. package/src/request/DeviceCodeRequest.ts +34 -0
  183. package/src/request/InteractiveRequest.ts +39 -0
  184. package/src/request/OnBehalfOfRequest.ts +30 -0
  185. package/src/request/RefreshTokenRequest.ts +34 -0
  186. package/src/request/SignOutRequest.ts +11 -0
  187. package/src/request/SilentFlowRequest.ts +32 -0
  188. package/src/request/UsernamePasswordRequest.ts +36 -0
  189. package/src/utils/Constants.ts +103 -0
  190. package/src/utils/EncodingUtils.ts +50 -0
  191. package/src/utils/NetworkUtils.ts +49 -0
@@ -0,0 +1,261 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ // AADAuthorityConstants
7
+
8
+ import { ClientApplication } from "./ClientApplication.js";
9
+ import { Configuration } from "../config/Configuration.js";
10
+ import { ClientAssertion } from "./ClientAssertion.js";
11
+ import {
12
+ Constants as NodeConstants,
13
+ ApiId,
14
+ REGION_ENVIRONMENT_VARIABLE,
15
+ } from "../utils/Constants.js";
16
+ import {
17
+ CommonClientCredentialRequest,
18
+ CommonOnBehalfOfRequest,
19
+ AuthenticationResult,
20
+ ClientAuthError,
21
+ AzureRegionConfiguration,
22
+ AuthError,
23
+ Constants,
24
+ IAppTokenProvider,
25
+ OIDC_DEFAULT_SCOPES,
26
+ UrlString,
27
+ AADAuthorityConstants,
28
+ } from "@azure/msal-common";
29
+ import { IConfidentialClientApplication } from "./IConfidentialClientApplication.js";
30
+ import { OnBehalfOfRequest } from "../request/OnBehalfOfRequest.js";
31
+ import { ClientCredentialRequest } from "../request/ClientCredentialRequest.js";
32
+ import { ClientCredentialClient } from "./ClientCredentialClient.js";
33
+ import { OnBehalfOfClient } from "./OnBehalfOfClient.js";
34
+
35
+ /**
36
+ * This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications
37
+ * will configure application secrets, client certificates/assertions as applicable
38
+ * @public
39
+ */
40
+ export class ConfidentialClientApplication
41
+ extends ClientApplication
42
+ implements IConfidentialClientApplication
43
+ {
44
+ private appTokenProvider?: IAppTokenProvider;
45
+
46
+ /**
47
+ * Constructor for the ConfidentialClientApplication
48
+ *
49
+ * Required attributes in the Configuration object are:
50
+ * - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal
51
+ * - authority: the authority URL for your application.
52
+ * - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.
53
+ *
54
+ * In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
55
+ * 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).
56
+ * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
57
+ * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
58
+ * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
59
+ *
60
+ * In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/
61
+ * Full B2C functionality will be available in this library in future versions.
62
+ *
63
+ * @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance
64
+ */
65
+ constructor(configuration: Configuration) {
66
+ super(configuration);
67
+ this.setClientCredential(this.config);
68
+ this.appTokenProvider = undefined;
69
+ }
70
+
71
+ /**
72
+ * This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and
73
+ * is meant for Azure SDK to enhance Managed Identity support.
74
+ *
75
+ * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source.
76
+ */
77
+ SetAppTokenProvider(provider: IAppTokenProvider): void {
78
+ this.appTokenProvider = provider;
79
+ }
80
+
81
+ /**
82
+ * Acquires tokens from the authority for the application (not for an end user).
83
+ */
84
+ public async acquireTokenByClientCredential(
85
+ request: ClientCredentialRequest
86
+ ): Promise<AuthenticationResult | null> {
87
+ this.logger.info(
88
+ "acquireTokenByClientCredential called",
89
+ request.correlationId
90
+ );
91
+
92
+ // If there is a client assertion present in the request, it overrides the one present in the client configuration
93
+ let clientAssertion;
94
+ if (request.clientAssertion) {
95
+ clientAssertion = {
96
+ assertion: request.clientAssertion,
97
+ assertionType: NodeConstants.JWT_BEARER_ASSERTION_TYPE,
98
+ };
99
+ }
100
+
101
+ const baseRequest = await this.initializeBaseRequest(request);
102
+
103
+ // valid base request should not contain oidc scopes in this grant type
104
+ const validBaseRequest = {
105
+ ...baseRequest,
106
+ scopes: baseRequest.scopes.filter(
107
+ (scope: string) => !OIDC_DEFAULT_SCOPES.includes(scope)
108
+ ),
109
+ };
110
+
111
+ const validRequest: CommonClientCredentialRequest = {
112
+ ...request,
113
+ ...validBaseRequest,
114
+ clientAssertion,
115
+ };
116
+
117
+ /*
118
+ * valid request should not have "common" or "organizations" in lieu of the tenant_id in the authority in the auth configuration
119
+ * example authority: "https://login.microsoftonline.com/TenantId",
120
+ */
121
+ const authority = new UrlString(validRequest.authority);
122
+ const tenantId = authority.getUrlComponents().PathSegments[0];
123
+ if (
124
+ Object.values(AADAuthorityConstants).includes(
125
+ tenantId as AADAuthorityConstants
126
+ )
127
+ ) {
128
+ throw ClientAuthError.createMissingTenantIdError();
129
+ }
130
+
131
+ const azureRegionConfiguration: AzureRegionConfiguration = {
132
+ azureRegion: validRequest.azureRegion,
133
+ environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE],
134
+ };
135
+
136
+ const serverTelemetryManager = this.initializeServerTelemetryManager(
137
+ ApiId.acquireTokenByClientCredential,
138
+ validRequest.correlationId,
139
+ validRequest.skipCache
140
+ );
141
+ try {
142
+ const clientCredentialConfig =
143
+ await this.buildOauthClientConfiguration(
144
+ validRequest.authority,
145
+ validRequest.correlationId,
146
+ serverTelemetryManager,
147
+ azureRegionConfiguration,
148
+ request.azureCloudOptions
149
+ );
150
+ const clientCredentialClient = new ClientCredentialClient(
151
+ clientCredentialConfig,
152
+ this.appTokenProvider
153
+ );
154
+ this.logger.verbose(
155
+ "Client credential client created",
156
+ validRequest.correlationId
157
+ );
158
+ return clientCredentialClient.acquireToken(validRequest);
159
+ } catch (e) {
160
+ if (e instanceof AuthError) {
161
+ e.setCorrelationId(validRequest.correlationId);
162
+ }
163
+ serverTelemetryManager.cacheFailedRequest(e);
164
+ throw e;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Acquires tokens from the authority for the application.
170
+ *
171
+ * Used in scenarios where the current app is a middle-tier service which was called with a token
172
+ * representing an end user. The current app can use the token (oboAssertion) to request another
173
+ * token to access downstream web API, on behalf of that user.
174
+ *
175
+ * The current middle-tier app has no user interaction to obtain consent.
176
+ * See how to gain consent upfront for your middle-tier app from this article.
177
+ * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application
178
+ */
179
+ public async acquireTokenOnBehalfOf(
180
+ request: OnBehalfOfRequest
181
+ ): Promise<AuthenticationResult | null> {
182
+ this.logger.info(
183
+ "acquireTokenOnBehalfOf called",
184
+ request.correlationId
185
+ );
186
+ const validRequest: CommonOnBehalfOfRequest = {
187
+ ...request,
188
+ ...(await this.initializeBaseRequest(request)),
189
+ };
190
+ try {
191
+ const onBehalfOfConfig = await this.buildOauthClientConfiguration(
192
+ validRequest.authority,
193
+ validRequest.correlationId,
194
+ undefined,
195
+ undefined,
196
+ request.azureCloudOptions
197
+ );
198
+ const oboClient = new OnBehalfOfClient(onBehalfOfConfig);
199
+ this.logger.verbose(
200
+ "On behalf of client created",
201
+ validRequest.correlationId
202
+ );
203
+ return oboClient.acquireToken(validRequest);
204
+ } catch (e) {
205
+ if (e instanceof AuthError) {
206
+ e.setCorrelationId(validRequest.correlationId);
207
+ }
208
+ throw e;
209
+ }
210
+ }
211
+
212
+ private setClientCredential(configuration: Configuration): void {
213
+ const clientSecretNotEmpty = !!configuration.auth.clientSecret;
214
+ const clientAssertionNotEmpty = !!configuration.auth.clientAssertion;
215
+ const certificate = configuration.auth.clientCertificate || {
216
+ thumbprint: Constants.EMPTY_STRING,
217
+ privateKey: Constants.EMPTY_STRING,
218
+ };
219
+ const certificateNotEmpty =
220
+ !!certificate.thumbprint || !!certificate.privateKey;
221
+
222
+ /*
223
+ * If app developer configures this callback, they don't need a credential
224
+ * i.e. AzureSDK can get token from Managed Identity without a cert / secret
225
+ */
226
+ if (this.appTokenProvider) {
227
+ return;
228
+ }
229
+
230
+ // Check that at most one credential is set on the application
231
+ if (
232
+ (clientSecretNotEmpty && clientAssertionNotEmpty) ||
233
+ (clientAssertionNotEmpty && certificateNotEmpty) ||
234
+ (clientSecretNotEmpty && certificateNotEmpty)
235
+ ) {
236
+ throw ClientAuthError.createInvalidCredentialError();
237
+ }
238
+
239
+ if (configuration.auth.clientSecret) {
240
+ this.clientSecret = configuration.auth.clientSecret;
241
+ return;
242
+ }
243
+
244
+ if (configuration.auth.clientAssertion) {
245
+ this.clientAssertion = ClientAssertion.fromAssertion(
246
+ configuration.auth.clientAssertion
247
+ );
248
+ return;
249
+ }
250
+
251
+ if (!certificateNotEmpty) {
252
+ throw ClientAuthError.createInvalidCredentialError();
253
+ } else {
254
+ this.clientAssertion = ClientAssertion.fromCertificate(
255
+ certificate.thumbprint,
256
+ certificate.privateKey,
257
+ configuration.auth.clientCertificate?.x5c
258
+ );
259
+ }
260
+ }
261
+ }
@@ -0,0 +1,360 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import {
7
+ AuthenticationResult,
8
+ BaseClient,
9
+ ClientAuthError,
10
+ ClientConfiguration,
11
+ CommonDeviceCodeRequest,
12
+ Constants,
13
+ DeviceCodeResponse,
14
+ GrantType,
15
+ RequestParameterBuilder,
16
+ RequestThumbprint,
17
+ ResponseHandler,
18
+ ServerAuthorizationTokenResponse,
19
+ ServerDeviceCodeResponse,
20
+ ServerError,
21
+ StringUtils,
22
+ TimeUtils,
23
+ UrlString,
24
+ } from "@azure/msal-common";
25
+
26
+ /**
27
+ * OAuth2.0 Device code client
28
+ */
29
+ export class DeviceCodeClient extends BaseClient {
30
+ constructor(configuration: ClientConfiguration) {
31
+ super(configuration);
32
+ }
33
+
34
+ /**
35
+ * Gets device code from device code endpoint, calls back to with device code response, and
36
+ * polls token endpoint to exchange device code for tokens
37
+ * @param request
38
+ */
39
+ public async acquireToken(
40
+ request: CommonDeviceCodeRequest
41
+ ): Promise<AuthenticationResult | null> {
42
+ const deviceCodeResponse: DeviceCodeResponse = await this.getDeviceCode(
43
+ request
44
+ );
45
+ request.deviceCodeCallback(deviceCodeResponse);
46
+ const reqTimestamp = TimeUtils.nowSeconds();
47
+ const response: ServerAuthorizationTokenResponse =
48
+ await this.acquireTokenWithDeviceCode(request, deviceCodeResponse);
49
+
50
+ const responseHandler = new ResponseHandler(
51
+ this.config.authOptions.clientId,
52
+ this.cacheManager,
53
+ this.cryptoUtils,
54
+ this.logger,
55
+ this.config.serializableCache,
56
+ this.config.persistencePlugin
57
+ );
58
+
59
+ // Validate response. This function throws a server error if an error is returned by the server.
60
+ responseHandler.validateTokenResponse(response);
61
+ return await responseHandler.handleServerTokenResponse(
62
+ response,
63
+ this.authority,
64
+ reqTimestamp,
65
+ request
66
+ );
67
+ }
68
+
69
+ /**
70
+ * Creates device code request and executes http GET
71
+ * @param request
72
+ */
73
+ private async getDeviceCode(
74
+ request: CommonDeviceCodeRequest
75
+ ): Promise<DeviceCodeResponse> {
76
+ const queryParametersString = this.createExtraQueryParameters(request);
77
+ const endpoint = UrlString.appendQueryString(
78
+ this.authority.deviceCodeEndpoint,
79
+ queryParametersString
80
+ );
81
+ const queryString = this.createQueryString(request);
82
+ const headers = this.createTokenRequestHeaders();
83
+ const thumbprint: RequestThumbprint = {
84
+ clientId: this.config.authOptions.clientId,
85
+ authority: request.authority,
86
+ scopes: request.scopes,
87
+ claims: request.claims,
88
+ authenticationScheme: request.authenticationScheme,
89
+ resourceRequestMethod: request.resourceRequestMethod,
90
+ resourceRequestUri: request.resourceRequestUri,
91
+ shrClaims: request.shrClaims,
92
+ sshKid: request.sshKid,
93
+ };
94
+
95
+ return this.executePostRequestToDeviceCodeEndpoint(
96
+ endpoint,
97
+ queryString,
98
+ headers,
99
+ thumbprint
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Creates query string for the device code request
105
+ * @param request
106
+ */
107
+ createExtraQueryParameters(request: CommonDeviceCodeRequest): string {
108
+ const parameterBuilder = new RequestParameterBuilder();
109
+
110
+ if (request.extraQueryParameters) {
111
+ parameterBuilder.addExtraQueryParameters(
112
+ request.extraQueryParameters
113
+ );
114
+ }
115
+
116
+ return parameterBuilder.createQueryString();
117
+ }
118
+
119
+ /**
120
+ * Executes POST request to device code endpoint
121
+ * @param deviceCodeEndpoint
122
+ * @param queryString
123
+ * @param headers
124
+ */
125
+ private async executePostRequestToDeviceCodeEndpoint(
126
+ deviceCodeEndpoint: string,
127
+ queryString: string,
128
+ headers: Record<string, string>,
129
+ thumbprint: RequestThumbprint
130
+ ): Promise<DeviceCodeResponse> {
131
+ const {
132
+ body: {
133
+ user_code: userCode,
134
+ device_code: deviceCode,
135
+ verification_uri: verificationUri,
136
+ expires_in: expiresIn,
137
+ interval,
138
+ message,
139
+ },
140
+ } = await this.networkManager.sendPostRequest<ServerDeviceCodeResponse>(
141
+ thumbprint,
142
+ deviceCodeEndpoint,
143
+ {
144
+ body: queryString,
145
+ headers: headers,
146
+ }
147
+ );
148
+
149
+ return {
150
+ userCode,
151
+ deviceCode,
152
+ verificationUri,
153
+ expiresIn,
154
+ interval,
155
+ message,
156
+ };
157
+ }
158
+
159
+ /**
160
+ * Create device code endpoint query parameters and returns string
161
+ */
162
+ private createQueryString(request: CommonDeviceCodeRequest): string {
163
+ const parameterBuilder: RequestParameterBuilder =
164
+ new RequestParameterBuilder();
165
+
166
+ parameterBuilder.addScopes(request.scopes);
167
+ parameterBuilder.addClientId(this.config.authOptions.clientId);
168
+
169
+ if (request.extraQueryParameters) {
170
+ parameterBuilder.addExtraQueryParameters(
171
+ request.extraQueryParameters
172
+ );
173
+ }
174
+
175
+ if (
176
+ request.claims ||
177
+ (this.config.authOptions.clientCapabilities &&
178
+ this.config.authOptions.clientCapabilities.length > 0)
179
+ ) {
180
+ parameterBuilder.addClaims(
181
+ request.claims,
182
+ this.config.authOptions.clientCapabilities
183
+ );
184
+ }
185
+
186
+ return parameterBuilder.createQueryString();
187
+ }
188
+
189
+ /**
190
+ * Breaks the polling with specific conditions.
191
+ * @param request CommonDeviceCodeRequest
192
+ * @param deviceCodeResponse DeviceCodeResponse
193
+ */
194
+ private continuePolling(
195
+ deviceCodeExpirationTime: number,
196
+ userSpecifiedTimeout?: number,
197
+ userSpecifiedCancelFlag?: boolean
198
+ ): boolean {
199
+ if (userSpecifiedCancelFlag) {
200
+ this.logger.error(
201
+ "Token request cancelled by setting DeviceCodeRequest.cancel = true"
202
+ );
203
+ throw ClientAuthError.createDeviceCodeCancelledError();
204
+ } else if (
205
+ userSpecifiedTimeout &&
206
+ userSpecifiedTimeout < deviceCodeExpirationTime &&
207
+ TimeUtils.nowSeconds() > userSpecifiedTimeout
208
+ ) {
209
+ this.logger.error(
210
+ `User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`
211
+ );
212
+ throw ClientAuthError.createUserTimeoutReachedError();
213
+ } else if (TimeUtils.nowSeconds() > deviceCodeExpirationTime) {
214
+ if (userSpecifiedTimeout) {
215
+ this.logger.verbose(
216
+ `User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`
217
+ );
218
+ }
219
+ this.logger.error(
220
+ `Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`
221
+ );
222
+ throw ClientAuthError.createDeviceCodeExpiredError();
223
+ }
224
+ return true;
225
+ }
226
+
227
+ /**
228
+ * Creates token request with device code response and polls token endpoint at interval set by the device code
229
+ * response
230
+ * @param request
231
+ * @param deviceCodeResponse
232
+ */
233
+ private async acquireTokenWithDeviceCode(
234
+ request: CommonDeviceCodeRequest,
235
+ deviceCodeResponse: DeviceCodeResponse
236
+ ): Promise<ServerAuthorizationTokenResponse> {
237
+ const queryParametersString = this.createTokenQueryParameters(request);
238
+ const endpoint = UrlString.appendQueryString(
239
+ this.authority.tokenEndpoint,
240
+ queryParametersString
241
+ );
242
+ const requestBody = this.createTokenRequestBody(
243
+ request,
244
+ deviceCodeResponse
245
+ );
246
+ const headers: Record<string, string> =
247
+ this.createTokenRequestHeaders();
248
+
249
+ const userSpecifiedTimeout = request.timeout
250
+ ? TimeUtils.nowSeconds() + request.timeout
251
+ : undefined;
252
+ const deviceCodeExpirationTime =
253
+ TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn;
254
+ const pollingIntervalMilli = deviceCodeResponse.interval * 1000;
255
+
256
+ /*
257
+ * Poll token endpoint while (device code is not expired AND operation has not been cancelled by
258
+ * setting CancellationToken.cancel = true). POST request is sent at interval set by pollingIntervalMilli
259
+ */
260
+ while (
261
+ this.continuePolling(
262
+ deviceCodeExpirationTime,
263
+ userSpecifiedTimeout,
264
+ request.cancel
265
+ )
266
+ ) {
267
+ const thumbprint: RequestThumbprint = {
268
+ clientId: this.config.authOptions.clientId,
269
+ authority: request.authority,
270
+ scopes: request.scopes,
271
+ claims: request.claims,
272
+ authenticationScheme: request.authenticationScheme,
273
+ resourceRequestMethod: request.resourceRequestMethod,
274
+ resourceRequestUri: request.resourceRequestUri,
275
+ shrClaims: request.shrClaims,
276
+ sshKid: request.sshKid,
277
+ };
278
+ const response = await this.executePostToTokenEndpoint(
279
+ endpoint,
280
+ requestBody,
281
+ headers,
282
+ thumbprint,
283
+ request.correlationId
284
+ );
285
+
286
+ if (response.body && response.body.error) {
287
+ // user authorization is pending. Sleep for polling interval and try again
288
+ if (response.body.error === Constants.AUTHORIZATION_PENDING) {
289
+ this.logger.info(
290
+ "Authorization pending. Continue polling."
291
+ );
292
+ await TimeUtils.delay(pollingIntervalMilli);
293
+ } else {
294
+ // for any other error, throw
295
+ this.logger.info(
296
+ "Unexpected error in polling from the server"
297
+ );
298
+ throw ServerError.createPostRequestFailed(
299
+ response.body.error
300
+ );
301
+ }
302
+ } else {
303
+ this.logger.verbose(
304
+ "Authorization completed successfully. Polling stopped."
305
+ );
306
+ return response.body;
307
+ }
308
+ }
309
+
310
+ /*
311
+ * The above code should've thrown by this point, but to satisfy TypeScript,
312
+ * and in the rare case the conditionals in continuePolling() may not catch everything...
313
+ */
314
+ this.logger.error("Polling stopped for unknown reasons.");
315
+ throw ClientAuthError.createDeviceCodeUnknownError();
316
+ }
317
+
318
+ /**
319
+ * Creates query parameters and converts to string.
320
+ * @param request
321
+ * @param deviceCodeResponse
322
+ */
323
+ private createTokenRequestBody(
324
+ request: CommonDeviceCodeRequest,
325
+ deviceCodeResponse: DeviceCodeResponse
326
+ ): string {
327
+ const requestParameters: RequestParameterBuilder =
328
+ new RequestParameterBuilder();
329
+
330
+ requestParameters.addScopes(request.scopes);
331
+ requestParameters.addClientId(this.config.authOptions.clientId);
332
+ requestParameters.addGrantType(GrantType.DEVICE_CODE_GRANT);
333
+ requestParameters.addDeviceCode(deviceCodeResponse.deviceCode);
334
+ const correlationId =
335
+ request.correlationId ||
336
+ this.config.cryptoInterface.createNewGuid();
337
+ requestParameters.addCorrelationId(correlationId);
338
+ requestParameters.addClientInfo();
339
+ requestParameters.addLibraryInfo(this.config.libraryInfo);
340
+ requestParameters.addApplicationTelemetry(
341
+ this.config.telemetry.application
342
+ );
343
+ requestParameters.addThrottling();
344
+ if (this.serverTelemetryManager) {
345
+ requestParameters.addServerTelemetry(this.serverTelemetryManager);
346
+ }
347
+
348
+ if (
349
+ !StringUtils.isEmptyObj(request.claims) ||
350
+ (this.config.authOptions.clientCapabilities &&
351
+ this.config.authOptions.clientCapabilities.length > 0)
352
+ ) {
353
+ requestParameters.addClaims(
354
+ request.claims,
355
+ this.config.authOptions.clientCapabilities
356
+ );
357
+ }
358
+ return requestParameters.createQueryString();
359
+ }
360
+ }
@@ -0,0 +1,72 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import {
7
+ AuthenticationResult,
8
+ IAppTokenProvider,
9
+ Logger,
10
+ } from "@azure/msal-common";
11
+ import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest.js";
12
+ import { AuthorizationUrlRequest } from "../request/AuthorizationUrlRequest.js";
13
+ import { ClientCredentialRequest } from "../request/ClientCredentialRequest.js";
14
+ import { OnBehalfOfRequest } from "../request/OnBehalfOfRequest.js";
15
+ import { RefreshTokenRequest } from "../request/RefreshTokenRequest.js";
16
+ import { SilentFlowRequest } from "../request/SilentFlowRequest.js";
17
+ import { UsernamePasswordRequest } from "../request/UsernamePasswordRequest.js";
18
+ import { TokenCache } from "../cache/TokenCache.js";
19
+
20
+ /**
21
+ * Interface for the ConfidentialClientApplication class defining the public API signatures
22
+ * @public
23
+ */
24
+ export interface IConfidentialClientApplication {
25
+ /** Creates the URL of the authorization request */
26
+ getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string>;
27
+
28
+ /** Acquires a token by exchanging the authorization code received from the first step of OAuth 2.0 Authorization Code Flow */
29
+ acquireTokenByCode(
30
+ request: AuthorizationCodeRequest
31
+ ): Promise<AuthenticationResult>;
32
+
33
+ /** Acquires a token silently when a user specifies the account the token is requested for */
34
+ acquireTokenSilent(
35
+ request: SilentFlowRequest
36
+ ): Promise<AuthenticationResult | null>;
37
+
38
+ /** Acquires a token by exchanging the refresh token provided for a new set of tokens */
39
+ acquireTokenByRefreshToken(
40
+ request: RefreshTokenRequest
41
+ ): Promise<AuthenticationResult | null>;
42
+
43
+ /** Acquires tokens from the authority for the application (not for an end user) */
44
+ acquireTokenByClientCredential(
45
+ request: ClientCredentialRequest
46
+ ): Promise<AuthenticationResult | null>;
47
+
48
+ /** Acquires tokens from the authority for the application */
49
+ acquireTokenOnBehalfOf(
50
+ request: OnBehalfOfRequest
51
+ ): Promise<AuthenticationResult | null>;
52
+
53
+ /** Acquires tokens with password grant by exchanging client applications username and password for credentials */
54
+ acquireTokenByUsernamePassword(
55
+ request: UsernamePasswordRequest
56
+ ): Promise<AuthenticationResult | null>;
57
+
58
+ /** Gets the token cache for the application */
59
+ getTokenCache(): TokenCache;
60
+
61
+ /** Returns the logger instance */
62
+ getLogger(): Logger;
63
+
64
+ /** Replaces the default logger set in configurations with new Logger with new configurations */
65
+ setLogger(logger: Logger): void;
66
+
67
+ /** Clear the cache */
68
+ clearCache(): void;
69
+
70
+ /** This extensibility point is meant for Azure SDK to enhance Managed Identity support */
71
+ SetAppTokenProvider(provider: IAppTokenProvider): void;
72
+ }