@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,165 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import jwt from "jsonwebtoken";
7
+ import {
8
+ TimeUtils,
9
+ Constants,
10
+ createClientAuthError,
11
+ ClientAuthErrorCodes,
12
+ } from "@azure/msal-common";
13
+ import { CryptoProvider } from "../crypto/CryptoProvider.js";
14
+ import { EncodingUtils } from "../utils/EncodingUtils.js";
15
+ import { JwtConstants } from "../utils/Constants.js";
16
+
17
+ /**
18
+ * Client assertion of type jwt-bearer used in confidential client flows
19
+ * @public
20
+ */
21
+ export class ClientAssertion {
22
+ private jwt: string;
23
+ private privateKey: string;
24
+ private thumbprint: string;
25
+ private expirationTime: number;
26
+ private issuer: string;
27
+ private jwtAudience: string;
28
+ private publicCertificate: Array<string>;
29
+
30
+ /**
31
+ * Initialize the ClientAssertion class from the clientAssertion passed by the user
32
+ * @param assertion - refer https://tools.ietf.org/html/rfc7521
33
+ */
34
+ public static fromAssertion(assertion: string): ClientAssertion {
35
+ const clientAssertion = new ClientAssertion();
36
+ clientAssertion.jwt = assertion;
37
+ return clientAssertion;
38
+ }
39
+
40
+ /**
41
+ * Initialize the ClientAssertion class from the certificate passed by the user
42
+ * @param thumbprint - identifier of a certificate
43
+ * @param privateKey - secret key
44
+ * @param publicCertificate - electronic document provided to prove the ownership of the public key
45
+ */
46
+ public static fromCertificate(
47
+ thumbprint: string,
48
+ privateKey: string,
49
+ publicCertificate?: string
50
+ ): ClientAssertion {
51
+ const clientAssertion = new ClientAssertion();
52
+ clientAssertion.privateKey = privateKey;
53
+ clientAssertion.thumbprint = thumbprint;
54
+ if (publicCertificate) {
55
+ clientAssertion.publicCertificate =
56
+ this.parseCertificate(publicCertificate);
57
+ }
58
+ return clientAssertion;
59
+ }
60
+
61
+ /**
62
+ * Update JWT for certificate based clientAssertion, if passed by the user, uses it as is
63
+ * @param cryptoProvider - library's crypto helper
64
+ * @param issuer - iss claim
65
+ * @param jwtAudience - aud claim
66
+ */
67
+ public getJwt(
68
+ cryptoProvider: CryptoProvider,
69
+ issuer: string,
70
+ jwtAudience: string
71
+ ): string {
72
+ // if assertion was created from certificate, check if jwt is expired and create new one.
73
+ if (this.privateKey && this.thumbprint) {
74
+ if (
75
+ this.jwt &&
76
+ !this.isExpired() &&
77
+ issuer === this.issuer &&
78
+ jwtAudience === this.jwtAudience
79
+ ) {
80
+ return this.jwt;
81
+ }
82
+
83
+ return this.createJwt(cryptoProvider, issuer, jwtAudience);
84
+ }
85
+
86
+ /*
87
+ * if assertion was created by caller, then we just append it. It is up to the caller to
88
+ * ensure that it contains necessary claims and that it is not expired.
89
+ */
90
+ if (this.jwt) {
91
+ return this.jwt;
92
+ }
93
+
94
+ throw createClientAuthError(ClientAuthErrorCodes.invalidAssertion);
95
+ }
96
+
97
+ /**
98
+ * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3
99
+ */
100
+ private createJwt(
101
+ cryptoProvider: CryptoProvider,
102
+ issuer: string,
103
+ jwtAudience: string
104
+ ): string {
105
+ this.issuer = issuer;
106
+ this.jwtAudience = jwtAudience;
107
+ const issuedAt = TimeUtils.nowSeconds();
108
+ this.expirationTime = issuedAt + 600;
109
+
110
+ const header: jwt.JwtHeader = {
111
+ alg: JwtConstants.RSA_256,
112
+ x5t: EncodingUtils.base64EncodeUrl(this.thumbprint, "hex"),
113
+ };
114
+
115
+ if (this.publicCertificate) {
116
+ Object.assign(header, {
117
+ x5c: this.publicCertificate,
118
+ } as Partial<jwt.JwtHeader>);
119
+ }
120
+
121
+ const payload = {
122
+ [JwtConstants.AUDIENCE]: this.jwtAudience,
123
+ [JwtConstants.EXPIRATION_TIME]: this.expirationTime,
124
+ [JwtConstants.ISSUER]: this.issuer,
125
+ [JwtConstants.SUBJECT]: this.issuer,
126
+ [JwtConstants.NOT_BEFORE]: issuedAt,
127
+ [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid(),
128
+ };
129
+
130
+ this.jwt = jwt.sign(payload, this.privateKey, { header });
131
+ return this.jwt;
132
+ }
133
+
134
+ /**
135
+ * Utility API to check expiration
136
+ */
137
+ private isExpired(): boolean {
138
+ return this.expirationTime < TimeUtils.nowSeconds();
139
+ }
140
+
141
+ /**
142
+ * Extracts the raw certs from a given certificate string and returns them in an array.
143
+ * @param publicCertificate - electronic document provided to prove the ownership of the public key
144
+ */
145
+ public static parseCertificate(publicCertificate: string): Array<string> {
146
+ /**
147
+ * This is regex to identify the certs in a given certificate string.
148
+ * We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines.
149
+ * The information in parens "(.+?)" is the capture group to represent the cert we want isolated.
150
+ * "." means any string character, "+" means match 1 or more times, and "?" means the shortest match.
151
+ * The "g" at the end of the regex means search the string globally, and the "s" enables the "." to match newlines.
152
+ */
153
+ const regexToFindCerts =
154
+ /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;
155
+ const certs: string[] = [];
156
+
157
+ let matches;
158
+ while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {
159
+ // matches[1] represents the first parens capture group in the regex.
160
+ certs.push(matches[1].replace(/\r*\n/g, Constants.EMPTY_STRING));
161
+ }
162
+
163
+ return certs;
164
+ }
165
+ }
@@ -0,0 +1,346 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import {
7
+ AccessTokenEntity,
8
+ AuthenticationResult,
9
+ AuthenticationScheme,
10
+ Authority,
11
+ BaseClient,
12
+ CacheOutcome,
13
+ ClientAuthErrorCodes,
14
+ ClientConfiguration,
15
+ CommonClientCredentialRequest,
16
+ Constants,
17
+ CredentialFilter,
18
+ CredentialType,
19
+ GrantType,
20
+ IAppTokenProvider,
21
+ RequestParameterBuilder,
22
+ RequestThumbprint,
23
+ ResponseHandler,
24
+ ScopeSet,
25
+ ServerAuthorizationTokenResponse,
26
+ StringUtils,
27
+ TimeUtils,
28
+ TokenCacheContext,
29
+ UrlString,
30
+ createClientAuthError,
31
+ } from "@azure/msal-common";
32
+
33
+ /**
34
+ * OAuth2.0 client credential grant
35
+ */
36
+ export class ClientCredentialClient extends BaseClient {
37
+ private scopeSet: ScopeSet;
38
+ private readonly appTokenProvider?: IAppTokenProvider;
39
+
40
+ constructor(
41
+ configuration: ClientConfiguration,
42
+ appTokenProvider?: IAppTokenProvider
43
+ ) {
44
+ super(configuration);
45
+ this.appTokenProvider = appTokenProvider;
46
+ }
47
+
48
+ /**
49
+ * Public API to acquire a token with ClientCredential Flow for Confidential clients
50
+ * @param request
51
+ */
52
+ public async acquireToken(
53
+ request: CommonClientCredentialRequest
54
+ ): Promise<AuthenticationResult | null> {
55
+ this.scopeSet = new ScopeSet(request.scopes || []);
56
+
57
+ if (request.skipCache) {
58
+ return await this.executeTokenRequest(request, this.authority);
59
+ }
60
+
61
+ const [cachedAuthenticationResult, lastCacheOutcome] =
62
+ await this.getCachedAuthenticationResult(request);
63
+
64
+ if (cachedAuthenticationResult) {
65
+ // if the token is not expired but must be refreshed; get a new one in the background
66
+ if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {
67
+ this.logger.info(
68
+ "ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."
69
+ );
70
+
71
+ // refresh the access token in the background
72
+ const refreshAccessToken = true;
73
+ await this.executeTokenRequest(
74
+ request,
75
+ this.authority,
76
+ refreshAccessToken
77
+ );
78
+ }
79
+
80
+ // return the cached token
81
+ return cachedAuthenticationResult;
82
+ } else {
83
+ return await this.executeTokenRequest(request, this.authority);
84
+ }
85
+ }
86
+
87
+ /**
88
+ * looks up cache if the tokens are cached already
89
+ */
90
+ private async getCachedAuthenticationResult(
91
+ request: CommonClientCredentialRequest
92
+ ): Promise<[AuthenticationResult | null, CacheOutcome]> {
93
+ let lastCacheOutcome: CacheOutcome = CacheOutcome.NOT_APPLICABLE;
94
+
95
+ // read the user-supplied cache into memory, if applicable
96
+ let cacheContext;
97
+ if (this.config.serializableCache && this.config.persistencePlugin) {
98
+ cacheContext = new TokenCacheContext(
99
+ this.config.serializableCache,
100
+ false
101
+ );
102
+ await this.config.persistencePlugin.beforeCacheAccess(cacheContext);
103
+ }
104
+
105
+ const cachedAccessToken = this.readAccessTokenFromCache();
106
+
107
+ if (
108
+ this.config.serializableCache &&
109
+ this.config.persistencePlugin &&
110
+ cacheContext
111
+ ) {
112
+ await this.config.persistencePlugin.afterCacheAccess(cacheContext);
113
+ }
114
+
115
+ // must refresh due to non-existent access_token
116
+ if (!cachedAccessToken) {
117
+ this.serverTelemetryManager?.setCacheOutcome(
118
+ CacheOutcome.NO_CACHED_ACCESS_TOKEN
119
+ );
120
+ return [null, CacheOutcome.NO_CACHED_ACCESS_TOKEN];
121
+ }
122
+
123
+ // must refresh due to the expires_in value
124
+ if (
125
+ TimeUtils.isTokenExpired(
126
+ cachedAccessToken.expiresOn,
127
+ this.config.systemOptions.tokenRenewalOffsetSeconds
128
+ )
129
+ ) {
130
+ this.serverTelemetryManager?.setCacheOutcome(
131
+ CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED
132
+ );
133
+ return [null, CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED];
134
+ }
135
+
136
+ // must refresh (in the background) due to the refresh_in value
137
+ if (
138
+ cachedAccessToken.refreshOn &&
139
+ TimeUtils.isTokenExpired(cachedAccessToken.refreshOn.toString(), 0)
140
+ ) {
141
+ lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
142
+ this.serverTelemetryManager?.setCacheOutcome(
143
+ CacheOutcome.PROACTIVELY_REFRESHED
144
+ );
145
+ }
146
+
147
+ return [
148
+ await ResponseHandler.generateAuthenticationResult(
149
+ this.cryptoUtils,
150
+ this.authority,
151
+ {
152
+ account: null,
153
+ idToken: null,
154
+ accessToken: cachedAccessToken,
155
+ refreshToken: null,
156
+ appMetadata: null,
157
+ },
158
+ true,
159
+ request
160
+ ),
161
+ lastCacheOutcome,
162
+ ];
163
+ }
164
+
165
+ /**
166
+ * Reads access token from the cache
167
+ */
168
+ private readAccessTokenFromCache(): AccessTokenEntity | null {
169
+ const accessTokenFilter: CredentialFilter = {
170
+ homeAccountId: Constants.EMPTY_STRING,
171
+ environment:
172
+ this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
173
+ credentialType: CredentialType.ACCESS_TOKEN,
174
+ clientId: this.config.authOptions.clientId,
175
+ realm: this.authority.tenant,
176
+ target: ScopeSet.createSearchScopes(this.scopeSet.asArray()),
177
+ };
178
+
179
+ const accessTokens =
180
+ this.cacheManager.getAccessTokensByFilter(accessTokenFilter);
181
+ if (accessTokens.length < 1) {
182
+ return null;
183
+ } else if (accessTokens.length > 1) {
184
+ throw createClientAuthError(
185
+ ClientAuthErrorCodes.multipleMatchingTokens
186
+ );
187
+ }
188
+ return accessTokens[0] as AccessTokenEntity;
189
+ }
190
+
191
+ /**
192
+ * Makes a network call to request the token from the service
193
+ * @param request
194
+ * @param authority
195
+ */
196
+ private async executeTokenRequest(
197
+ request: CommonClientCredentialRequest,
198
+ authority: Authority,
199
+ refreshAccessToken?: boolean
200
+ ): Promise<AuthenticationResult | null> {
201
+ let serverTokenResponse: ServerAuthorizationTokenResponse;
202
+ let reqTimestamp: number;
203
+
204
+ if (this.appTokenProvider) {
205
+ this.logger.info("Using appTokenProvider extensibility.");
206
+
207
+ const appTokenPropviderParameters = {
208
+ correlationId: request.correlationId,
209
+ tenantId: this.config.authOptions.authority.tenant,
210
+ scopes: request.scopes,
211
+ claims: request.claims,
212
+ };
213
+
214
+ reqTimestamp = TimeUtils.nowSeconds();
215
+ const appTokenProviderResult = await this.appTokenProvider(
216
+ appTokenPropviderParameters
217
+ );
218
+
219
+ serverTokenResponse = {
220
+ access_token: appTokenProviderResult.accessToken,
221
+ expires_in: appTokenProviderResult.expiresInSeconds,
222
+ refresh_in: appTokenProviderResult.refreshInSeconds,
223
+ token_type: AuthenticationScheme.BEARER,
224
+ };
225
+ } else {
226
+ const queryParametersString =
227
+ this.createTokenQueryParameters(request);
228
+ const endpoint = UrlString.appendQueryString(
229
+ authority.tokenEndpoint,
230
+ queryParametersString
231
+ );
232
+ const requestBody = this.createTokenRequestBody(request);
233
+ const headers: Record<string, string> =
234
+ this.createTokenRequestHeaders();
235
+ const thumbprint: RequestThumbprint = {
236
+ clientId: this.config.authOptions.clientId,
237
+ authority: request.authority,
238
+ scopes: request.scopes,
239
+ claims: request.claims,
240
+ authenticationScheme: request.authenticationScheme,
241
+ resourceRequestMethod: request.resourceRequestMethod,
242
+ resourceRequestUri: request.resourceRequestUri,
243
+ shrClaims: request.shrClaims,
244
+ sshKid: request.sshKid,
245
+ };
246
+
247
+ reqTimestamp = TimeUtils.nowSeconds();
248
+ const response = await this.executePostToTokenEndpoint(
249
+ endpoint,
250
+ requestBody,
251
+ headers,
252
+ thumbprint,
253
+ request.correlationId
254
+ );
255
+
256
+ serverTokenResponse = response.body;
257
+ serverTokenResponse.status = response.status;
258
+ }
259
+
260
+ const responseHandler = new ResponseHandler(
261
+ this.config.authOptions.clientId,
262
+ this.cacheManager,
263
+ this.cryptoUtils,
264
+ this.logger,
265
+ this.config.serializableCache,
266
+ this.config.persistencePlugin
267
+ );
268
+
269
+ responseHandler.validateTokenResponse(
270
+ serverTokenResponse,
271
+ refreshAccessToken
272
+ );
273
+
274
+ const tokenResponse = await responseHandler.handleServerTokenResponse(
275
+ serverTokenResponse,
276
+ this.authority,
277
+ reqTimestamp,
278
+ request
279
+ );
280
+
281
+ return tokenResponse;
282
+ }
283
+
284
+ /**
285
+ * generate the request to the server in the acceptable format
286
+ * @param request
287
+ */
288
+ private createTokenRequestBody(
289
+ request: CommonClientCredentialRequest
290
+ ): string {
291
+ const parameterBuilder = new RequestParameterBuilder();
292
+
293
+ parameterBuilder.addClientId(this.config.authOptions.clientId);
294
+
295
+ parameterBuilder.addScopes(request.scopes, false);
296
+
297
+ parameterBuilder.addGrantType(GrantType.CLIENT_CREDENTIALS_GRANT);
298
+
299
+ parameterBuilder.addLibraryInfo(this.config.libraryInfo);
300
+ parameterBuilder.addApplicationTelemetry(
301
+ this.config.telemetry.application
302
+ );
303
+
304
+ parameterBuilder.addThrottling();
305
+
306
+ if (this.serverTelemetryManager) {
307
+ parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
308
+ }
309
+
310
+ const correlationId =
311
+ request.correlationId ||
312
+ this.config.cryptoInterface.createNewGuid();
313
+ parameterBuilder.addCorrelationId(correlationId);
314
+
315
+ if (this.config.clientCredentials.clientSecret) {
316
+ parameterBuilder.addClientSecret(
317
+ this.config.clientCredentials.clientSecret
318
+ );
319
+ }
320
+
321
+ // Use clientAssertion from request, fallback to client assertion in base configuration
322
+ const clientAssertion =
323
+ request.clientAssertion ||
324
+ this.config.clientCredentials.clientAssertion;
325
+
326
+ if (clientAssertion) {
327
+ parameterBuilder.addClientAssertion(clientAssertion.assertion);
328
+ parameterBuilder.addClientAssertionType(
329
+ clientAssertion.assertionType
330
+ );
331
+ }
332
+
333
+ if (
334
+ !StringUtils.isEmptyObj(request.claims) ||
335
+ (this.config.authOptions.clientCapabilities &&
336
+ this.config.authOptions.clientCapabilities.length > 0)
337
+ ) {
338
+ parameterBuilder.addClaims(
339
+ request.claims,
340
+ this.config.authOptions.clientCapabilities
341
+ );
342
+ }
343
+
344
+ return parameterBuilder.createQueryString();
345
+ }
346
+ }