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