@azure/identity 1.3.0 → 1.5.2

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.

Potentially problematic release.


This version of @azure/identity might be problematic. Click here for more details.

Files changed (54) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +8 -1
  3. package/dist/index.js +233 -168
  4. package/dist/index.js.map +1 -1
  5. package/dist-esm/src/client/identityClient.js +92 -51
  6. package/dist-esm/src/client/identityClient.js.map +1 -1
  7. package/dist-esm/src/client/msalClient.js.map +1 -1
  8. package/dist-esm/src/constants.js +5 -0
  9. package/dist-esm/src/constants.js.map +1 -1
  10. package/dist-esm/src/credentials/authorizationCodeCredential.browser.js.map +1 -1
  11. package/dist-esm/src/credentials/authorizationCodeCredential.js +8 -7
  12. package/dist-esm/src/credentials/authorizationCodeCredential.js.map +1 -1
  13. package/dist-esm/src/credentials/azureCliCredential.browser.js.map +1 -1
  14. package/dist-esm/src/credentials/azureCliCredential.js.map +1 -1
  15. package/dist-esm/src/credentials/chainedTokenCredential.js.map +1 -1
  16. package/dist-esm/src/credentials/clientCertificateCredential.browser.js.map +1 -1
  17. package/dist-esm/src/credentials/clientCertificateCredential.js +8 -7
  18. package/dist-esm/src/credentials/clientCertificateCredential.js.map +1 -1
  19. package/dist-esm/src/credentials/clientSecretCredential.js +10 -9
  20. package/dist-esm/src/credentials/clientSecretCredential.js.map +1 -1
  21. package/dist-esm/src/credentials/deviceCodeCredential.browser.js.map +1 -1
  22. package/dist-esm/src/credentials/deviceCodeCredential.js.map +1 -1
  23. package/dist-esm/src/credentials/environmentCredential.browser.js.map +1 -1
  24. package/dist-esm/src/credentials/environmentCredential.js.map +1 -1
  25. package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js +2 -3
  26. package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js.map +1 -1
  27. package/dist-esm/src/credentials/interactiveBrowserCredential.js.map +1 -1
  28. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js +11 -5
  29. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js.map +1 -1
  30. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js +16 -9
  31. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js.map +1 -1
  32. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js +4 -3
  33. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js.map +1 -1
  34. package/dist-esm/src/credentials/managedIdentityCredential/constants.js +2 -1
  35. package/dist-esm/src/credentials/managedIdentityCredential/constants.js.map +1 -1
  36. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js +6 -4
  37. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js.map +1 -1
  38. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js +42 -21
  39. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js.map +1 -1
  40. package/dist-esm/src/credentials/managedIdentityCredential/index.browser.js.map +1 -1
  41. package/dist-esm/src/credentials/managedIdentityCredential/index.js +1 -1
  42. package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
  43. package/dist-esm/src/credentials/managedIdentityCredential/models.js.map +1 -1
  44. package/dist-esm/src/credentials/managedIdentityCredential/utils.js +6 -2
  45. package/dist-esm/src/credentials/managedIdentityCredential/utils.js.map +1 -1
  46. package/dist-esm/src/credentials/usernamePasswordCredential.js +8 -7
  47. package/dist-esm/src/credentials/usernamePasswordCredential.js.map +1 -1
  48. package/dist-esm/src/credentials/visualStudioCodeCredential.browser.js.map +1 -1
  49. package/dist-esm/src/credentials/visualStudioCodeCredential.js.map +1 -1
  50. package/dist-esm/src/index.js.map +1 -1
  51. package/dist-esm/src/util/isNode.js +10 -0
  52. package/dist-esm/src/util/isNode.js.map +1 -0
  53. package/package.json +6 -7
  54. package/types/identity.d.ts +7 -6
@@ -1 +1 @@
1
- {"version":3,"file":"clientCertificateCredential.js","sourceRoot":"","sources":["../../../src/credent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aACX;oBAAS;gBACR,IAAI,CAAC,GAAG,EAAE,CAAC;aACZ;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport qs from \"qs\";\nimport jws from \"jws\";\nimport { v4 as uuidV4 } from \"uuid\";\nimport { readFileSync } from \"fs\";\nimport { createHash } from \"crypto\";\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-http\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport { ClientCertificateCredentialOptions } from \"./clientCertificateCredentialOptions\";\nimport { createSpan } from \"../util/tracing\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { credentialLogger, formatSuccess, formatError } from \"../util/logging\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { checkTenantId } from \"../util/checkTenantId\";\n\nconst SelfSignedJwtLifetimeMins = 10;\n\nfunction timestampInSeconds(date: Date): number {\n return Math.floor(date.getTime() / 1000);\n}\n\nfunction addMinutes(date: Date, minutes: number): Date {\n date.setMinutes(date.getMinutes() + minutes);\n return date;\n}\n\nconst logger = credentialLogger(\"ClientCertificateCredential\");\n\n/**\n * Enables authentication to Azure Active Directory using a PEM-encoded\n * certificate that is assigned to an App Registration. More information\n * on how to configure certificate authentication can be found here:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad\n *\n */\nexport class ClientCertificateCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private clientId: string;\n private certificateString: string;\n private certificateThumbprint: string;\n private certificateX5t: string;\n private certificateX5c?: Array<string>;\n\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Azure Active Directory with a certificate.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param certificatePath - The path to a PEM-encoded public/private key certificate on the filesystem.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n certificatePath: string,\n options?: ClientCertificateCredentialOptions\n ) {\n checkTenantId(logger, tenantId);\n\n this.identityClient = new IdentityClient(options);\n this.tenantId = tenantId;\n this.clientId = clientId;\n this.certificateString = readFileSync(certificatePath, \"utf8\");\n\n const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(this.certificateString);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n const error = new Error(\n \"The file at the specified path does not contain a PEM-encoded certificate.\"\n );\n logger.info(formatError(\"\", error));\n throw error;\n }\n\n this.certificateThumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n this.certificateX5t = Buffer.from(this.certificateThumbprint, \"hex\").toString(\"base64\");\n if (options && options.sendCertificateChain) {\n this.certificateX5c = publicKeys;\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span, updatedOptions: newOptions } = createSpan(\n \"ClientCertificateCredential-getToken\",\n options\n );\n try {\n const tokenId = uuidV4();\n const urlSuffix = getIdentityTokenEndpointSuffix(this.tenantId);\n const audienceUrl = `${this.identityClient.authorityHost}/${this.tenantId}/${urlSuffix}`;\n let header: jws.Header;\n\n if (this.certificateX5c) {\n header = {\n typ: \"JWT\",\n alg: \"RS256\",\n x5t: this.certificateX5t,\n x5c: this.certificateX5c\n };\n } else {\n header = {\n typ: \"JWT\",\n alg: \"RS256\",\n x5t: this.certificateX5t\n };\n }\n\n const payload = {\n iss: this.clientId,\n sub: this.clientId,\n aud: audienceUrl,\n jti: tokenId,\n nbf: timestampInSeconds(new Date()),\n exp: timestampInSeconds(addMinutes(new Date(), SelfSignedJwtLifetimeMins))\n };\n\n const clientAssertion = jws.sign({\n header,\n payload,\n secret: this.certificateString\n });\n\n const webResource = this.identityClient.createWebResource({\n url: audienceUrl,\n method: \"POST\",\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n body: qs.stringify({\n response_type: \"token\",\n grant_type: \"client_credentials\",\n client_id: this.clientId,\n client_assertion_type: \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n client_assertion: clientAssertion,\n scope: typeof scopes === \"string\" ? scopes : scopes.join(\" \")\n }),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n abortSignal: options && options.abortSignal,\n spanOptions: newOptions.tracingOptions && newOptions.tracingOptions.spanOptions,\n tracingContext: newOptions.tracingOptions && newOptions.tracingOptions.tracingContext,\n });\n\n const tokenResponse = await this.identityClient.sendTokenRequest(webResource);\n logger.getToken.info(formatSuccess(scopes));\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n logger.getToken.info(formatError(\"\", err));\n throw err;\n } finally {\n span.end();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"clientCertificateCredential.js","sourceRoot":"","sources":["../../../src/credentials/clientCertificateCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAE,YA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qBAAqB,EAAE,wDAAwD;wBAC/E,gBAAgB,EAAE,eAAe;wBACjC,KAAK,EAAE,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;qBAC9D,CAAC;oBACF,OAAO,EAAE,iBAAiB,CAAC;wBACzB,MAAM,EAAE,kBAAkB;wBAC1B,cAAc,EAAE,mCAAmC;qBACpD,CAAC;oBACF,WAAW,EAAE,OAAO,IAAI,OAAO,CAAC,WAAW;oBAC3C,cAAc,EAAE;wBACd,WAAW,EAAE,UAAU,CAAC,cAAc,IAAI,UAAU,CAAC,cAAc,CAAC,WAAW;wBAC/E,cAAc,EAAE,UAAU,CAAC,cAAc,IAAI,UAAU,CAAC,cAAc,CAAC,cAAc;qBACtF;iBACF,CAAC,CAAC;gBAEH,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;gBAC9E,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;gBAC5C,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;aAC7D;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,CAAC,SAAS,CAAC;oBACb,IAAI,EAAE,cAAc,CAAC,KAAK;oBAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;iBACrB,CAAC,CAAC;gBACH,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC;gBAC3C,MAAM,GAAG,CAAC;aACX;oBAAS;gBACR,IAAI,CAAC,GAAG,EAAE,CAAC;aACZ;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport qs from \"qs\";\nimport jws from \"jws\";\nimport { v4 as uuidV4 } from \"uuid\";\nimport { readFileSync } from \"fs\";\nimport { createHash } from \"crypto\";\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-auth\";\nimport { createPipelineRequest, createHttpHeaders } from \"@azure/core-rest-pipeline\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport { ClientCertificateCredentialOptions } from \"./clientCertificateCredentialOptions\";\nimport { createSpan } from \"../util/tracing\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { credentialLogger, formatSuccess, formatError } from \"../util/logging\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { checkTenantId } from \"../util/checkTenantId\";\n\nconst SelfSignedJwtLifetimeMins = 10;\n\nfunction timestampInSeconds(date: Date): number {\n return Math.floor(date.getTime() / 1000);\n}\n\nfunction addMinutes(date: Date, minutes: number): Date {\n date.setMinutes(date.getMinutes() + minutes);\n return date;\n}\n\nconst logger = credentialLogger(\"ClientCertificateCredential\");\n\n/**\n * Enables authentication to Azure Active Directory using a PEM-encoded\n * certificate that is assigned to an App Registration. More information\n * on how to configure certificate authentication can be found here:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad\n *\n */\nexport class ClientCertificateCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private clientId: string;\n private certificateString: string;\n private certificateThumbprint: string;\n private certificateX5t: string;\n private certificateX5c?: Array<string>;\n\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Azure Active Directory with a certificate.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param certificatePath - The path to a PEM-encoded public/private key certificate on the filesystem.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n certificatePath: string,\n options?: ClientCertificateCredentialOptions\n ) {\n checkTenantId(logger, tenantId);\n\n this.identityClient = new IdentityClient(options);\n this.tenantId = tenantId;\n this.clientId = clientId;\n this.certificateString = readFileSync(certificatePath, \"utf8\");\n\n const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(this.certificateString);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n const error = new Error(\n \"The file at the specified path does not contain a PEM-encoded certificate.\"\n );\n logger.info(formatError(\"\", error));\n throw error;\n }\n\n this.certificateThumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n this.certificateX5t = Buffer.from(this.certificateThumbprint, \"hex\").toString(\"base64\");\n if (options && options.sendCertificateChain) {\n this.certificateX5c = publicKeys;\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span, updatedOptions: newOptions } = createSpan(\n \"ClientCertificateCredential-getToken\",\n options\n );\n try {\n const tokenId = uuidV4();\n const urlSuffix = getIdentityTokenEndpointSuffix(this.tenantId);\n const audienceUrl = `${this.identityClient.authorityHost}/${this.tenantId}/${urlSuffix}`;\n let header: jws.Header;\n\n if (this.certificateX5c) {\n header = {\n typ: \"JWT\",\n alg: \"RS256\",\n x5t: this.certificateX5t,\n x5c: this.certificateX5c\n };\n } else {\n header = {\n typ: \"JWT\",\n alg: \"RS256\",\n x5t: this.certificateX5t\n };\n }\n\n const payload = {\n iss: this.clientId,\n sub: this.clientId,\n aud: audienceUrl,\n jti: tokenId,\n nbf: timestampInSeconds(new Date()),\n exp: timestampInSeconds(addMinutes(new Date(), SelfSignedJwtLifetimeMins))\n };\n\n const clientAssertion = jws.sign({\n header,\n payload,\n secret: this.certificateString\n });\n\n const webResource = createPipelineRequest({\n url: audienceUrl,\n method: \"POST\",\n body: qs.stringify({\n response_type: \"token\",\n grant_type: \"client_credentials\",\n client_id: this.clientId,\n client_assertion_type: \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n client_assertion: clientAssertion,\n scope: typeof scopes === \"string\" ? scopes : scopes.join(\" \")\n }),\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n }),\n abortSignal: options && options.abortSignal,\n tracingOptions: {\n spanOptions: newOptions.tracingOptions && newOptions.tracingOptions.spanOptions,\n tracingContext: newOptions.tracingOptions && newOptions.tracingOptions.tracingContext\n }\n });\n\n const tokenResponse = await this.identityClient.sendTokenRequest(webResource);\n logger.getToken.info(formatSuccess(scopes));\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n logger.getToken.info(formatError(\"\", err));\n throw err;\n } finally {\n span.end();\n }\n }\n}\n"]}
@@ -2,6 +2,7 @@
2
2
  // Licensed under the MIT license.
3
3
  import { __awaiter } from "tslib";
4
4
  import qs from "qs";
5
+ import { createPipelineRequest, createHttpHeaders } from "@azure/core-rest-pipeline";
5
6
  import { IdentityClient } from "../client/identityClient";
6
7
  import { createSpan } from "../util/tracing";
7
8
  import { SpanStatusCode } from "@azure/core-tracing";
@@ -45,14 +46,12 @@ export class ClientSecretCredential {
45
46
  */
46
47
  getToken(scopes, options) {
47
48
  return __awaiter(this, void 0, void 0, function* () {
48
- const { span, updatedOptions: newOptions } = createSpan("ClientSecretCredential-getToken", options);
49
+ const { span, updatedOptions } = createSpan("ClientSecretCredential-getToken", options);
49
50
  try {
50
51
  const urlSuffix = getIdentityTokenEndpointSuffix(this.tenantId);
51
- const webResource = this.identityClient.createWebResource({
52
+ const request = createPipelineRequest({
52
53
  url: `${this.identityClient.authorityHost}/${this.tenantId}/${urlSuffix}`,
53
54
  method: "POST",
54
- disableJsonStringifyOnBody: true,
55
- deserializationMapper: undefined,
56
55
  body: qs.stringify({
57
56
  response_type: "token",
58
57
  grant_type: "client_credentials",
@@ -60,15 +59,17 @@ export class ClientSecretCredential {
60
59
  client_secret: this.clientSecret,
61
60
  scope: typeof scopes === "string" ? scopes : scopes.join(" ")
62
61
  }),
63
- headers: {
62
+ headers: createHttpHeaders({
64
63
  Accept: "application/json",
65
64
  "Content-Type": "application/x-www-form-urlencoded"
66
- },
65
+ }),
67
66
  abortSignal: options && options.abortSignal,
68
- spanOptions: newOptions.tracingOptions && newOptions.tracingOptions.spanOptions,
69
- tracingContext: newOptions.tracingOptions && newOptions.tracingOptions.tracingContext,
67
+ tracingOptions: {
68
+ spanOptions: updatedOptions.tracingOptions && updatedOptions.tracingOptions.spanOptions,
69
+ tracingContext: updatedOptions.tracingOptions && updatedOptions.tracingOptions.tracingContext
70
+ }
70
71
  });
71
- const tokenResponse = yield this.identityClient.sendTokenRequest(webResource);
72
+ const tokenResponse = yield this.identityClient.sendTokenRequest(request);
72
73
  logger.getToken.info(formatSuccess(scopes));
73
74
  return (tokenResponse && tokenResponse.accessToken) || null;
74
75
  }
@@ -1 +1 @@
1
- {"version":3,"file":"clientSecretCredential.js","sourceRoot":"","sources":["../../../src/credentials/clientSecretCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,EAA0B,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAClF,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,gBAAgB,E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,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;qBAC9D,CAAC;oBACF,OAAO,EAAE;wBACP,MAAM,EAAE,kBAAkB;wBAC1B,cAAc,EAAE,mCAAmC;qBACpD;oBACD,WAAW,EAAE,OAAO,IAAI,OAAO,CAAC,WAAW;oBAC3C,WAAW,EAAE,UAAU,CAAC,cAAc,IAAI,UAAU,CAAC,cAAc,CAAC,WAAW;oBAC/E,cAAc,EAAE,UAAU,CAAC,cAAc,IAAI,UAAU,CAAC,cAAc,CAAC,cAAc;iBACtF,CAAC,CAAC;gBAEH,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;gBAC9E,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;gBAC5C,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;aAC7D;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,CAAC,SAAS,CAAC;oBACb,IAAI,EAAE,cAAc,CAAC,KAAK;oBAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;iBACrB,CAAC,CAAC;gBACH,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;gBAC/C,MAAM,GAAG,CAAC;aACX;oBAAS;gBACR,IAAI,CAAC,GAAG,EAAE,CAAC;aACZ;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport qs from \"qs\";\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-http\";\nimport { TokenCredentialOptions, IdentityClient } from \"../client/identityClient\";\nimport { createSpan } from \"../util/tracing\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\n\nconst logger = credentialLogger(\"ClientSecretCredential\");\n\n/**\n * Enables authentication to Azure Active Directory using a client secret\n * that was generated for an App Registration. More information on how\n * to configure a client secret can be found here:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application\n *\n */\nexport class ClientSecretCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private clientId: string;\n private clientSecret: string;\n\n /**\n * Creates an instance of the ClientSecretCredential with the details\n * needed to authenticate against Azure Active Directory with a client\n * secret.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n clientSecret: string,\n options?: TokenCredentialOptions\n ) {\n this.identityClient = new IdentityClient(options);\n this.tenantId = tenantId;\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span, updatedOptions: newOptions } = createSpan(\"ClientSecretCredential-getToken\", options);\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(this.tenantId);\n const webResource = this.identityClient.createWebResource({\n url: `${this.identityClient.authorityHost}/${this.tenantId}/${urlSuffix}`,\n method: \"POST\",\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n body: qs.stringify({\n response_type: \"token\",\n grant_type: \"client_credentials\",\n client_id: this.clientId,\n client_secret: this.clientSecret,\n scope: typeof scopes === \"string\" ? scopes : scopes.join(\" \")\n }),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n abortSignal: options && options.abortSignal,\n spanOptions: newOptions.tracingOptions && newOptions.tracingOptions.spanOptions,\n tracingContext: newOptions.tracingOptions && newOptions.tracingOptions.tracingContext,\n });\n\n const tokenResponse = await this.identityClient.sendTokenRequest(webResource);\n logger.getToken.info(formatSuccess(scopes));\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n logger.getToken.info(formatError(scopes, err));\n throw err;\n } finally {\n span.end();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"clientSecretCredential.js","sourceRoot":"","sources":["../../../src/credentials/clientSecretCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AACrF,OAAO,EAA0B,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAClF,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAE/E,MAAM,MAAM,GAAG,gBAAgB,CAAC,wBAAwB,CAAC,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,OAAO,sBAAsB;IAMjC;;;;;;;;;OASG;IACH,YACE,QAAgB,EAChB,QAAgB,EAChB,YAAoB,EACpB,OAAgC;QAEhC,IAAI,CAAC,cAAc,GAAG,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QA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C,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;gBAC5C,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;aAC7D;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,CAAC,SAAS,CAAC;oBACb,IAAI,EAAE,cAAc,CAAC,KAAK;oBAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;iBACrB,CAAC,CAAC;gBACH,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;gBAC/C,MAAM,GAAG,CAAC;aACX;oBAAS;gBACR,IAAI,CAAC,GAAG,EAAE,CAAC;aACZ;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport qs from \"qs\";\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-auth\";\nimport { createPipelineRequest, createHttpHeaders } from \"@azure/core-rest-pipeline\";\nimport { TokenCredentialOptions, IdentityClient } from \"../client/identityClient\";\nimport { createSpan } from \"../util/tracing\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\n\nconst logger = credentialLogger(\"ClientSecretCredential\");\n\n/**\n * Enables authentication to Azure Active Directory using a client secret\n * that was generated for an App Registration. More information on how\n * to configure a client secret can be found here:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application\n *\n */\nexport class ClientSecretCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private clientId: string;\n private clientSecret: string;\n\n /**\n * Creates an instance of the ClientSecretCredential with the details\n * needed to authenticate against Azure Active Directory with a client\n * secret.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n clientSecret: string,\n options?: TokenCredentialOptions\n ) {\n this.identityClient = new IdentityClient(options);\n this.tenantId = tenantId;\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span, updatedOptions } = createSpan(\"ClientSecretCredential-getToken\", options);\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(this.tenantId);\n const request = createPipelineRequest({\n url: `${this.identityClient.authorityHost}/${this.tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: qs.stringify({\n response_type: \"token\",\n grant_type: \"client_credentials\",\n client_id: this.clientId,\n client_secret: this.clientSecret,\n scope: typeof scopes === \"string\" ? scopes : scopes.join(\" \")\n }),\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n }),\n abortSignal: options && options.abortSignal,\n tracingOptions: {\n spanOptions: updatedOptions.tracingOptions && updatedOptions.tracingOptions.spanOptions,\n tracingContext:\n updatedOptions.tracingOptions && updatedOptions.tracingOptions.tracingContext\n }\n });\n\n const tokenResponse = await this.identityClient.sendTokenRequest(request);\n logger.getToken.info(formatSuccess(scopes));\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n logger.getToken.info(formatError(scopes, err));\n throw err;\n } finally {\n span.end();\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"deviceCodeCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/deviceCodeCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;AACpG,MAAM,MAAM,GAAG,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;AAExD,MAAM,OAAO,oBAAoB;IAC/B;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TokenCredential, AccessToken } from \"@azure/core-http\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\"DeviceCodeCredential is not supported in the browser.\");\nconst logger = credentialLogger(\"DeviceCodeCredential\");\n\nexport class DeviceCodeCredential implements TokenCredential {\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}
1
+ {"version":3,"file":"deviceCodeCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/deviceCodeCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;AACpG,MAAM,MAAM,GAAG,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;AAExD,MAAM,OAAO,oBAAoB;IAC/B;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TokenCredential, AccessToken } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\"DeviceCodeCredential is not supported in the browser.\");\nconst logger = credentialLogger(\"DeviceCodeCredential\");\n\nexport class DeviceCodeCredential implements TokenCredential {\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"deviceCodeCredential.js","sourceRoot":"","sources":["../../../src/credentials/deviceCodeCredential.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAIrD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAiCvD,MAAM,MAA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aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;oBAC5C,OAAO;wBACL,kBAAkB;wBAClB,KAAK,EAAE,cAAc,CAAC,WAAW;qBAClC,CAAC;iBACH;qBAAM;oBACL,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;iBAClE;aACF;YAAC,OAAO,KAAK,EAAE;gBACd,MAAM,IAAI,KAAK,CAAC,gCAAgC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;aAC3E;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-http\";\nimport { AuthenticationRequired, MsalClient } from \"../client/msalClient\";\nimport { createSpan } from \"../util/tracing\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { TokenCredentialOptions } from \"../client/identityClient\";\n\nimport { DeviceCodeRequest } from \"@azure/msal-node\";\nimport { checkTenantId } from \"../util/checkTenantId\";\nimport { DeveloperSignOnClientId } from \"../constants\";\n\n/**\n * Provides the user code and verification URI where the code must be\n * entered. Also provides a message to display to the user which\n * contains an instruction with these details.\n */\nexport interface DeviceCodeInfo {\n /**\n * The device code that the user must enter into the verification page.\n */\n userCode: string;\n\n /**\n * The verification URI to which the user must navigate to enter the device\n * code.\n */\n verificationUri: string;\n\n /**\n * A message that may be shown to the user to instruct them on how to enter\n * the device code in the page specified by the verification URI.\n */\n message: string;\n}\n\n/**\n * Defines the signature of a callback which will be passed to\n * DeviceCodeCredential for the purpose of displaying authentication\n * details to the user.\n */\nexport type DeviceCodePromptCallback = (deviceCodeInfo: DeviceCodeInfo) => void;\n\nconst logger = credentialLogger(\"DeviceCodeCredential\");\n\n/**\n * Method that logs the user code from the DeviceCodeCredential.\n * @param deviceCodeInfo - The device code.\n */\nexport function defaultDeviceCodePromptCallback(deviceCodeInfo: DeviceCodeInfo): void {\n console.log(deviceCodeInfo.message);\n}\n\n/**\n * Enables authentication to Azure Active Directory using a device code\n * that the user can enter into https://microsoft.com/devicelogin.\n */\nexport class DeviceCodeCredential implements TokenCredential {\n private userPromptCallback: DeviceCodePromptCallback;\n private msalClient: MsalClient;\n\n /**\n * Creates an instance of DeviceCodeCredential with the details needed\n * to initiate the device code authorization flow with Azure Active Directory.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID or name.\n * The default value is 'organizations'.\n * 'organizations' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * By default we will try to use the Azure CLI's client ID to authenticate.\n * @param userPromptCallback - A callback function that will be invoked to show\n {@link DeviceCodeInfo} to the user. If left unassigned, we will automatically log the device code information and the authentication instructions in the console.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string = \"organizations\",\n clientId: string = DeveloperSignOnClientId,\n userPromptCallback: DeviceCodePromptCallback = defaultDeviceCodePromptCallback,\n options?: TokenCredentialOptions\n ) {\n checkTenantId(logger, tenantId);\n\n this.userPromptCallback = userPromptCallback;\n\n let authorityHost;\n if (options && options.authorityHost) {\n if (options.authorityHost.endsWith(\"/\")) {\n authorityHost = options.authorityHost + tenantId;\n } else {\n authorityHost = options.authorityHost + \"/\" + tenantId;\n }\n } else {\n authorityHost = \"https://login.microsoftonline.com/\" + tenantId;\n }\n\n this.msalClient = new MsalClient(\n { clientId: clientId, authority: authorityHost },\n false,\n undefined,\n options\n );\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span } = createSpan(\"DeviceCodeCredential-getToken\", options);\n\n const scopeArray = typeof scopes === \"object\" ? scopes : [scopes];\n\n const deviceCodeRequest = {\n deviceCodeCallback: this.userPromptCallback,\n scopes: scopeArray\n };\n\n logger.info(`DeviceCodeCredential invoked. Scopes: ${scopeArray.join(\", \")}`);\n\n return this.msalClient.acquireTokenFromCache(scopeArray).catch(async (e) => {\n if (e instanceof AuthenticationRequired) {\n try {\n const token = await this.acquireTokenByDeviceCode(deviceCodeRequest, scopeArray);\n logger.getToken.info(formatSuccess(scopeArray));\n return token;\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n logger.getToken.info(formatError(scopeArray, err));\n throw err;\n } finally {\n span.end();\n }\n } else {\n throw e;\n }\n });\n }\n\n private async acquireTokenByDeviceCode(\n deviceCodeRequest: DeviceCodeRequest,\n scopes: string[]\n ): Promise<AccessToken | null> {\n try {\n const deviceResponse = await this.msalClient.acquireTokenByDeviceCode(deviceCodeRequest);\n if (deviceResponse && deviceResponse.expiresOn) {\n const expiresOnTimestamp = deviceResponse.expiresOn.getTime();\n logger.getToken.info(formatSuccess(scopes));\n return {\n expiresOnTimestamp,\n token: deviceResponse.accessToken\n };\n } else {\n throw new Error(\"Did not receive token with a valid expiration\");\n }\n } catch (error) {\n throw new Error(`Device Authentication Error \"${JSON.stringify(error)}\"`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"deviceCodeCredential.js","sourceRoot":"","sources":["../../../src/credentials/deviceCodeCredential.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAIrD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,uBAAuB,EAA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,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;oBAC5C,OAAO;wBACL,kBAAkB;wBAClB,KAAK,EAAE,cAAc,CAAC,WAAW;qBAClC,CAAC;iBACH;qBAAM;oBACL,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;iBAClE;aACF;YAAC,OAAO,KAAK,EAAE;gBACd,MAAM,IAAI,KAAK,CAAC,gCAAgC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;aAC3E;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRequired, MsalClient } from \"../client/msalClient\";\nimport { createSpan } from \"../util/tracing\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { TokenCredentialOptions } from \"../client/identityClient\";\n\nimport { DeviceCodeRequest } from \"@azure/msal-node\";\nimport { checkTenantId } from \"../util/checkTenantId\";\nimport { DeveloperSignOnClientId } from \"../constants\";\n\n/**\n * Provides the user code and verification URI where the code must be\n * entered. Also provides a message to display to the user which\n * contains an instruction with these details.\n */\nexport interface DeviceCodeInfo {\n /**\n * The device code that the user must enter into the verification page.\n */\n userCode: string;\n\n /**\n * The verification URI to which the user must navigate to enter the device\n * code.\n */\n verificationUri: string;\n\n /**\n * A message that may be shown to the user to instruct them on how to enter\n * the device code in the page specified by the verification URI.\n */\n message: string;\n}\n\n/**\n * Defines the signature of a callback which will be passed to\n * DeviceCodeCredential for the purpose of displaying authentication\n * details to the user.\n */\nexport type DeviceCodePromptCallback = (deviceCodeInfo: DeviceCodeInfo) => void;\n\nconst logger = credentialLogger(\"DeviceCodeCredential\");\n\n/**\n * Method that logs the user code from the DeviceCodeCredential.\n * @param deviceCodeInfo - The device code.\n */\nexport function defaultDeviceCodePromptCallback(deviceCodeInfo: DeviceCodeInfo): void {\n console.log(deviceCodeInfo.message);\n}\n\n/**\n * Enables authentication to Azure Active Directory using a device code\n * that the user can enter into https://microsoft.com/devicelogin.\n */\nexport class DeviceCodeCredential implements TokenCredential {\n private userPromptCallback: DeviceCodePromptCallback;\n private msalClient: MsalClient;\n\n /**\n * Creates an instance of DeviceCodeCredential with the details needed\n * to initiate the device code authorization flow with Azure Active Directory.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID or name.\n * The default value is 'organizations'.\n * 'organizations' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * By default we will try to use the Azure CLI's client ID to authenticate.\n * @param userPromptCallback - A callback function that will be invoked to show\n {@link DeviceCodeInfo} to the user. If left unassigned, we will automatically log the device code information and the authentication instructions in the console.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string = \"organizations\",\n clientId: string = DeveloperSignOnClientId,\n userPromptCallback: DeviceCodePromptCallback = defaultDeviceCodePromptCallback,\n options?: TokenCredentialOptions\n ) {\n checkTenantId(logger, tenantId);\n\n this.userPromptCallback = userPromptCallback;\n\n let authorityHost;\n if (options && options.authorityHost) {\n if (options.authorityHost.endsWith(\"/\")) {\n authorityHost = options.authorityHost + tenantId;\n } else {\n authorityHost = options.authorityHost + \"/\" + tenantId;\n }\n } else {\n authorityHost = \"https://login.microsoftonline.com/\" + tenantId;\n }\n\n this.msalClient = new MsalClient(\n { clientId: clientId, authority: authorityHost },\n false,\n undefined,\n options\n );\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span } = createSpan(\"DeviceCodeCredential-getToken\", options);\n\n const scopeArray = typeof scopes === \"object\" ? scopes : [scopes];\n\n const deviceCodeRequest = {\n deviceCodeCallback: this.userPromptCallback,\n scopes: scopeArray\n };\n\n logger.info(`DeviceCodeCredential invoked. Scopes: ${scopeArray.join(\", \")}`);\n\n return this.msalClient.acquireTokenFromCache(scopeArray).catch(async (e) => {\n if (e instanceof AuthenticationRequired) {\n try {\n const token = await this.acquireTokenByDeviceCode(deviceCodeRequest, scopeArray);\n logger.getToken.info(formatSuccess(scopeArray));\n return token;\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n logger.getToken.info(formatError(scopeArray, err));\n throw err;\n } finally {\n span.end();\n }\n } else {\n throw e;\n }\n });\n }\n\n private async acquireTokenByDeviceCode(\n deviceCodeRequest: DeviceCodeRequest,\n scopes: string[]\n ): Promise<AccessToken | null> {\n try {\n const deviceResponse = await this.msalClient.acquireTokenByDeviceCode(deviceCodeRequest);\n if (deviceResponse && deviceResponse.expiresOn) {\n const expiresOnTimestamp = deviceResponse.expiresOn.getTime();\n logger.getToken.info(formatSuccess(scopes));\n return {\n expiresOnTimestamp,\n token: deviceResponse.accessToken\n };\n } else {\n throw new Error(\"Did not receive token with a valid expiration\");\n }\n } catch (error) {\n throw new Error(`Device Authentication Error \"${JSON.stringify(error)}\"`);\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"environmentCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/environmentCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,wDAAwD,CACzD,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,uBAAuB,CAAC,CAAC;AAEzD,MAAM,OAAO,qBAAqB;IAChC;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAED,QAAQ;QACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-http\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"EnvironmentCredential is not supported in the browser.\"\n);\nconst logger = credentialLogger(\"EnvironmentCredential\");\n\nexport class EnvironmentCredential implements TokenCredential {\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}
1
+ {"version":3,"file":"environmentCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/environmentCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,wDAAwD,CACzD,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,uBAAuB,CAAC,CAAC;AAEzD,MAAM,OAAO,qBAAqB;IAChC;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAED,QAAQ;QACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"EnvironmentCredential is not supported in the browser.\"\n);\nconst logger = credentialLogger(\"EnvironmentCredential\");\n\nexport class EnvironmentCredential implements TokenCredential {\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"environmentCredential.js","sourceRoot":"","sources":["../../../src/credentials/environmentCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAIlC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC/F,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG;IAC9C,iBAAiB;IACjB,iBAAiB;IACjB,qBAAqB;IACrB,+BAA+B;IAC/B,gBAAgB;IAChB,gBAAgB;CACjB,CAAC;AAEF,MAAM,MAAM,GAAG,gBAAgB,CAAC,uBAAuB,CAAC,CAAC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3B;wBAAS;oBACR,IAAI,CAAC,GAAG,EAAE,CAAC;iBACZ;aACF;YAED,0EAA0E;YAC1E,iEAAiE;YACjE,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,cAAc,CAAC,KAAK,EAAE,CAAC,CAAC;YAC/C,IAAI,CAAC,GAAG,EAAE,CAAC;YACX,MAAM,KAAK,GAAG,IAAI,qBAAqB,CACrC,uFAAuF,CACxF,CAAC;YACF,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;YACjD,MAAM,KAAK,CAAC;QACd,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-http\";\nimport { TokenCredentialOptions } from \"../client/identityClient\";\nimport { ClientSecretCredential } from \"./clientSecretCredential\";\nimport { createSpan } from \"../util/tracing\";\nimport {\n AuthenticationError,\n CredentialUnavailable\n} from \"../client/errors\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { ClientCertificateCredential } from \"./clientCertificateCredential\";\nimport { UsernamePasswordCredential } from \"./usernamePasswordCredential\";\nimport { credentialLogger, processEnvVars, formatSuccess, formatError } from \"../util/logging\";\nimport { checkTenantId } from \"../util/checkTenantId\";\n\n/**\n * Contains the list of all supported environment variable names so that an\n * appropriate error message can be generated when no credentials can be\n * configured.\n *\n * @internal\n */\nexport const AllSupportedEnvironmentVariables = [\n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_CLIENT_SECRET\",\n \"AZURE_CLIENT_CERTIFICATE_PATH\",\n \"AZURE_USERNAME\",\n \"AZURE_PASSWORD\"\n];\n\nconst logger = credentialLogger(\"EnvironmentCredential\");\n\n/**\n * Enables authentication to Azure Active Directory using client secret\n * details configured in the following environment variables:\n *\n * - AZURE_TENANT_ID: The Azure Active Directory tenant (directory) ID.\n * - AZURE_CLIENT_ID: The client (application) ID of an App Registration in the tenant.\n * - AZURE_CLIENT_SECRET: A client secret that was generated for the App Registration.\n *\n * This credential ultimately uses a {@link ClientSecretCredential} to\n * perform the authentication using these details. Please consult the\n * documentation of that class for more details.\n */\nexport class EnvironmentCredential implements TokenCredential {\n private _credential?: TokenCredential = undefined;\n /**\n * Creates an instance of the EnvironmentCredential class and reads\n * client secret details from environment variables. If the expected\n * environment variables are not found at this time, the getToken method\n * will return null when invoked.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: TokenCredentialOptions) {\n // Keep track of any missing environment variables for error details\n\n const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(\", \");\n logger.info(`Found the following environment variables: ${assigned}`);\n\n const tenantId = process.env.AZURE_TENANT_ID,\n clientId = process.env.AZURE_CLIENT_ID,\n clientSecret = process.env.AZURE_CLIENT_SECRET;\n\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n\n if (tenantId && clientId && clientSecret) {\n logger.info(\n `Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`\n );\n this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);\n return;\n }\n\n const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;\n if (tenantId && clientId && certificatePath) {\n logger.info(\n `Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`\n );\n this._credential = new ClientCertificateCredential(\n tenantId,\n clientId,\n certificatePath,\n options\n );\n return;\n }\n\n const username = process.env.AZURE_USERNAME;\n const password = process.env.AZURE_PASSWORD;\n if (tenantId && clientId && username && password) {\n logger.info(\n `Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`\n );\n this._credential = new UsernamePasswordCredential(\n tenantId,\n clientId,\n username,\n password,\n options\n );\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span, updatedOptions: newOptions } = createSpan(\"EnvironmentCredential-getToken\", options);\n if (this._credential) {\n try {\n const result = await this._credential.getToken(scopes, newOptions);\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n const authenticationError = new AuthenticationError(400, {\n error: \"EnvironmentCredential authentication failed.\",\n error_description: err.message\n .toString()\n .split(\"More details:\")\n .join(\"\")\n });\n logger.getToken.info(formatError(scopes, authenticationError));\n throw authenticationError;\n } finally {\n span.end();\n }\n }\n\n // If by this point we don't have a credential, throw an exception so that\n // the user knows the credential was not configured appropriately\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n const error = new CredentialUnavailable(\n \"EnvironmentCredential is unavailable. Environment variables are not fully configured.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n}\n"]}
1
+ {"version":3,"file":"environmentCredential.js","sourceRoot":"","sources":["../../../src/credentials/environmentCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAIlC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,aAAa,E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AAE;wBACvD,KAAK,EAAE,8CAA8C;wBACrD,iBAAiB,EAAE,GAAG,CAAC,OAAO;6BAC3B,QAAQ,EAAE;6BACV,KAAK,CAAC,eAAe,CAAC;6BACtB,IAAI,CAAC,EAAE,CAAC;qBACZ,CAAC,CAAC;oBACH,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC;oBAC/D,MAAM,mBAAmB,CAAC;iBAC3B;wBAAS;oBACR,IAAI,CAAC,GAAG,EAAE,CAAC;iBACZ;aACF;YAED,0EAA0E;YAC1E,iEAAiE;YACjE,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,cAAc,CAAC,KAAK,EAAE,CAAC,CAAC;YAC/C,IAAI,CAAC,GAAG,EAAE,CAAC;YACX,MAAM,KAAK,GAAG,IAAI,qBAAqB,CACrC,uFAAuF,CACxF,CAAC;YACF,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;YACjD,MAAM,KAAK,CAAC;QACd,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-auth\";\nimport { TokenCredentialOptions } from \"../client/identityClient\";\nimport { ClientSecretCredential } from \"./clientSecretCredential\";\nimport { createSpan } from \"../util/tracing\";\nimport { AuthenticationError, CredentialUnavailable } from \"../client/errors\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { ClientCertificateCredential } from \"./clientCertificateCredential\";\nimport { UsernamePasswordCredential } from \"./usernamePasswordCredential\";\nimport { credentialLogger, processEnvVars, formatSuccess, formatError } from \"../util/logging\";\nimport { checkTenantId } from \"../util/checkTenantId\";\n\n/**\n * Contains the list of all supported environment variable names so that an\n * appropriate error message can be generated when no credentials can be\n * configured.\n *\n * @internal\n */\nexport const AllSupportedEnvironmentVariables = [\n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_CLIENT_SECRET\",\n \"AZURE_CLIENT_CERTIFICATE_PATH\",\n \"AZURE_USERNAME\",\n \"AZURE_PASSWORD\"\n];\n\nconst logger = credentialLogger(\"EnvironmentCredential\");\n\n/**\n * Enables authentication to Azure Active Directory using client secret\n * details configured in the following environment variables:\n *\n * - AZURE_TENANT_ID: The Azure Active Directory tenant (directory) ID.\n * - AZURE_CLIENT_ID: The client (application) ID of an App Registration in the tenant.\n * - AZURE_CLIENT_SECRET: A client secret that was generated for the App Registration.\n *\n * This credential ultimately uses a {@link ClientSecretCredential} to\n * perform the authentication using these details. Please consult the\n * documentation of that class for more details.\n */\nexport class EnvironmentCredential implements TokenCredential {\n private _credential?: TokenCredential = undefined;\n /**\n * Creates an instance of the EnvironmentCredential class and reads\n * client secret details from environment variables. If the expected\n * environment variables are not found at this time, the getToken method\n * will return null when invoked.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: TokenCredentialOptions) {\n // Keep track of any missing environment variables for error details\n\n const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(\", \");\n logger.info(`Found the following environment variables: ${assigned}`);\n\n const tenantId = process.env.AZURE_TENANT_ID,\n clientId = process.env.AZURE_CLIENT_ID,\n clientSecret = process.env.AZURE_CLIENT_SECRET;\n\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n\n if (tenantId && clientId && clientSecret) {\n logger.info(\n `Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`\n );\n this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);\n return;\n }\n\n const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;\n if (tenantId && clientId && certificatePath) {\n logger.info(\n `Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`\n );\n this._credential = new ClientCertificateCredential(\n tenantId,\n clientId,\n certificatePath,\n options\n );\n return;\n }\n\n const username = process.env.AZURE_USERNAME;\n const password = process.env.AZURE_PASSWORD;\n if (tenantId && clientId && username && password) {\n logger.info(\n `Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`\n );\n this._credential = new UsernamePasswordCredential(\n tenantId,\n clientId,\n username,\n password,\n options\n );\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span, updatedOptions: newOptions } = createSpan(\n \"EnvironmentCredential-getToken\",\n options\n );\n if (this._credential) {\n try {\n const result = await this._credential.getToken(scopes, newOptions);\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n const authenticationError = new AuthenticationError(400, {\n error: \"EnvironmentCredential authentication failed.\",\n error_description: err.message\n .toString()\n .split(\"More details:\")\n .join(\"\")\n });\n logger.getToken.info(formatError(scopes, authenticationError));\n throw authenticationError;\n } finally {\n span.end();\n }\n }\n\n // If by this point we don't have a credential, throw an exception so that\n // the user knows the credential was not configured appropriately\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n const error = new CredentialUnavailable(\n \"EnvironmentCredential is unavailable. Environment variables are not fully configured.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n}\n"]}
@@ -2,10 +2,9 @@
2
2
  // Licensed under the MIT license.
3
3
  import { __awaiter } from "tslib";
4
4
  import * as msal from "msal";
5
- import { IdentityClient } from "../client/identityClient";
6
5
  import { createSpan } from "../util/tracing";
7
6
  import { SpanStatusCode } from "@azure/core-tracing";
8
- import { DefaultTenantId, DeveloperSignOnClientId } from "../constants";
7
+ import { DefaultAuthorityHost, DefaultTenantId, DeveloperSignOnClientId } from "../constants";
9
8
  import { credentialLogger, formatSuccess, formatError } from "../util/logging";
10
9
  const logger = credentialLogger("InteractiveBrowserCredential");
11
10
  /**
@@ -24,7 +23,7 @@ export class InteractiveBrowserCredential {
24
23
  * @param options - Options for configuring the client which makes the authentication request.
25
24
  */
26
25
  constructor(options) {
27
- options = Object.assign(Object.assign(Object.assign({}, IdentityClient.getDefaultOptions()), options), { tenantId: (options && options.tenantId) || DefaultTenantId,
26
+ options = Object.assign(Object.assign({ authorityHost: DefaultAuthorityHost }, options), { tenantId: (options && options.tenantId) || DefaultTenantId,
28
27
  // TODO: temporary - this is the Azure CLI clientID - we'll replace it when
29
28
  // Developer Sign On application is available
30
29
  // https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/identity/Azure.Identity/src/Constants.cs#L9
@@ -1 +1 @@
1
- {"version":3,"file":"interactiveBrowserCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/interactiveBrowserCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAK1D,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE/E,MAAM,MAAM,GAAG,gBAAgB,CAAC,8BAA8B,CAAC,CAAC;AAEhE;;;;GAIG;AACH,MAAM,OAAO,4BAA4B;IAKvC;;;;;;;;OAQG;IACH,YAAY,OAA6C;QACvD,OAAO,iDACF,cAAc,CAAC,iBAAiB,EAAE,GAClC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C,MAAM,CAAC,CAAC,CAAC;oBAC5C,OAAO;wBACL,KAAK,EAAE,YAAY,CAAC,WAAW;wBAC/B,kBAAkB;qBACnB,CAAC;iBACH;qBAAM;oBACL,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;oBACpC,OAAO,IAAI,CAAC;iBACb;aACF;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,CAAC,SAAS,CAAC;oBACb,IAAI,EAAE,cAAc,CAAC,KAAK;oBAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;iBACrB,CAAC,CAAC;gBACH,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;gBAC/C,MAAM,GAAG,CAAC;aACX;oBAAS;gBACR,IAAI,CAAC,GAAG,EAAE,CAAC;aACZ;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msal from \"msal\";\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-http\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport {\n BrowserLoginStyle,\n InteractiveBrowserCredentialOptions\n} from \"./interactiveBrowserCredentialOptions\";\nimport { createSpan } from \"../util/tracing\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { DefaultTenantId, DeveloperSignOnClientId } from \"../constants\";\nimport { credentialLogger, formatSuccess, formatError } from \"../util/logging\";\n\nconst logger = credentialLogger(\"InteractiveBrowserCredential\");\n\n/**\n * Enables authentication to Azure Active Directory inside of the web browser\n * using the interactive login flow, either via browser redirects or a popup\n * window.\n */\nexport class InteractiveBrowserCredential implements TokenCredential {\n private loginStyle: BrowserLoginStyle;\n private msalConfig: msal.Configuration;\n private msalObject: msal.UserAgentApplication;\n\n /**\n * Creates an instance of the InteractiveBrowserCredential with the\n * details needed to authenticate against Azure Active Directory with\n * a user identity.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: InteractiveBrowserCredentialOptions) {\n options = {\n ...IdentityClient.getDefaultOptions(),\n ...options,\n tenantId: (options && options.tenantId) || DefaultTenantId,\n // TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n // Developer Sign On application is available\n // https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/identity/Azure.Identity/src/Constants.cs#L9\n clientId: (options && options.clientId) || DeveloperSignOnClientId\n };\n\n this.loginStyle = options.loginStyle || \"popup\";\n if ([\"redirect\", \"popup\"].indexOf(this.loginStyle) === -1) {\n const error = new Error(`Invalid loginStyle: ${options.loginStyle}`);\n logger.info(formatError(\"\", error));\n throw error;\n }\n\n const knownAuthorities =\n options.tenantId === \"adfs\" ? (options.authorityHost ? [options.authorityHost] : []) : [];\n\n this.msalConfig = {\n auth: {\n clientId: options.clientId!, // we just initialized it above\n authority: `${options.authorityHost}/${options.tenantId}`,\n knownAuthorities,\n ...(options.redirectUri && { redirectUri: options.redirectUri }),\n ...(options.postLogoutRedirectUri && { redirectUri: options.postLogoutRedirectUri })\n },\n cache: {\n cacheLocation: \"localStorage\",\n storeAuthStateInCookie: true\n }\n };\n\n this.msalObject = new msal.UserAgentApplication(this.msalConfig);\n }\n\n private login(): Promise<msal.AuthResponse> {\n switch (this.loginStyle) {\n case \"redirect\": {\n const loginPromise = new Promise<msal.AuthResponse>((resolve, reject) => {\n this.msalObject.handleRedirectCallback(resolve, reject);\n });\n this.msalObject.loginRedirect();\n return loginPromise;\n }\n case \"popup\":\n return this.msalObject.loginPopup();\n }\n }\n\n private async acquireToken(\n authParams: msal.AuthenticationParameters\n ): Promise<msal.AuthResponse | undefined> {\n let authResponse: msal.AuthResponse | undefined;\n try {\n logger.info(\"Attempting to acquire token silently\");\n authResponse = await this.msalObject.acquireTokenSilent(authParams);\n } catch (err) {\n if (err instanceof msal.AuthError) {\n switch (err.errorCode) {\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n logger.info(`Authentication returned errorCode ${err.errorCode}`);\n break;\n default:\n logger.info(formatError(authParams.scopes, `Failed to acquire token: ${err.message}`));\n throw err;\n }\n }\n }\n\n let authPromise: Promise<msal.AuthResponse> | undefined;\n if (authResponse === undefined) {\n logger.info(\n `Silent authentication failed, falling back to interactive method ${this.loginStyle}`\n );\n switch (this.loginStyle) {\n case \"redirect\":\n authPromise = new Promise((resolve, reject) => {\n this.msalObject.handleRedirectCallback(resolve, reject);\n });\n this.msalObject.acquireTokenRedirect(authParams);\n break;\n case \"popup\":\n authPromise = this.msalObject.acquireTokenPopup(authParams);\n break;\n }\n\n authResponse = authPromise && (await authPromise);\n }\n\n return authResponse;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span } = createSpan(\"InteractiveBrowserCredential-getToken\", options);\n try {\n if (!this.msalObject.getAccount()) {\n await this.login();\n }\n\n const authResponse = await this.acquireToken({\n scopes: Array.isArray(scopes) ? scopes : scopes.split(\",\")\n });\n\n if (authResponse) {\n const expiresOnTimestamp = authResponse.expiresOn.getTime();\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: authResponse.accessToken,\n expiresOnTimestamp\n };\n } else {\n logger.getToken.info(\"No response\");\n return null;\n }\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n logger.getToken.info(formatError(scopes, err));\n throw err;\n } finally {\n span.end();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"interactiveBrowserCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/interactiveBrowserCredential.browser.ts"],"names":[],"mappings":"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uCAAuC,EAAE,OAAO,CAAC,CAAC;YAC9E,IAAI;gBACF,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,EAAE;oBACjC,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;iBACpB;gBAED,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC;oBAC3C,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC;iBAC3D,CAAC,CAAC;gBAEH,IAAI,YAAY,EAAE;oBAChB,MAAM,kBAAkB,GAAG,YAAY,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;oBAC5D,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;oBAC5C,OAAO;wBACL,KAAK,EAAE,YAAY,CAAC,WAAW;wBAC/B,kBAAkB;qBACnB,CAAC;iBACH;qBAAM;oBACL,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;oBACpC,OAAO,IAAI,CAAC;iBACb;aACF;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,CAAC,SAAS,CAAC;oBACb,IAAI,EAAE,cAAc,CAAC,KAAK;oBAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;iBACrB,CAAC,CAAC;gBACH,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;gBAC/C,MAAM,GAAG,CAAC;aACX;oBAAS;gBACR,IAAI,CAAC,GAAG,EAAE,CAAC;aACZ;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msal from \"msal\";\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-auth\";\nimport {\n BrowserLoginStyle,\n InteractiveBrowserCredentialOptions\n} from \"./interactiveBrowserCredentialOptions\";\nimport { createSpan } from \"../util/tracing\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { DefaultAuthorityHost, DefaultTenantId, DeveloperSignOnClientId } from \"../constants\";\nimport { credentialLogger, formatSuccess, formatError } from \"../util/logging\";\n\nconst logger = credentialLogger(\"InteractiveBrowserCredential\");\n\n/**\n * Enables authentication to Azure Active Directory inside of the web browser\n * using the interactive login flow, either via browser redirects or a popup\n * window.\n */\nexport class InteractiveBrowserCredential implements TokenCredential {\n private loginStyle: BrowserLoginStyle;\n private msalConfig: msal.Configuration;\n private msalObject: msal.UserAgentApplication;\n\n /**\n * Creates an instance of the InteractiveBrowserCredential with the\n * details needed to authenticate against Azure Active Directory with\n * a user identity.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: InteractiveBrowserCredentialOptions) {\n options = {\n authorityHost: DefaultAuthorityHost,\n ...options,\n tenantId: (options && options.tenantId) || DefaultTenantId,\n // TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n // Developer Sign On application is available\n // https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/identity/Azure.Identity/src/Constants.cs#L9\n clientId: (options && options.clientId) || DeveloperSignOnClientId\n };\n\n this.loginStyle = options.loginStyle || \"popup\";\n if ([\"redirect\", \"popup\"].indexOf(this.loginStyle) === -1) {\n const error = new Error(`Invalid loginStyle: ${options.loginStyle}`);\n logger.info(formatError(\"\", error));\n throw error;\n }\n\n const knownAuthorities =\n options.tenantId === \"adfs\" ? (options.authorityHost ? [options.authorityHost] : []) : [];\n\n this.msalConfig = {\n auth: {\n clientId: options.clientId!, // we just initialized it above\n authority: `${options.authorityHost}/${options.tenantId}`,\n knownAuthorities,\n ...(options.redirectUri && { redirectUri: options.redirectUri }),\n ...(options.postLogoutRedirectUri && { redirectUri: options.postLogoutRedirectUri })\n },\n cache: {\n cacheLocation: \"localStorage\",\n storeAuthStateInCookie: true\n }\n };\n\n this.msalObject = new msal.UserAgentApplication(this.msalConfig);\n }\n\n private login(): Promise<msal.AuthResponse> {\n switch (this.loginStyle) {\n case \"redirect\": {\n const loginPromise = new Promise<msal.AuthResponse>((resolve, reject) => {\n this.msalObject.handleRedirectCallback(resolve, reject);\n });\n this.msalObject.loginRedirect();\n return loginPromise;\n }\n case \"popup\":\n return this.msalObject.loginPopup();\n }\n }\n\n private async acquireToken(\n authParams: msal.AuthenticationParameters\n ): Promise<msal.AuthResponse | undefined> {\n let authResponse: msal.AuthResponse | undefined;\n try {\n logger.info(\"Attempting to acquire token silently\");\n authResponse = await this.msalObject.acquireTokenSilent(authParams);\n } catch (err) {\n if (err instanceof msal.AuthError) {\n switch (err.errorCode) {\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n logger.info(`Authentication returned errorCode ${err.errorCode}`);\n break;\n default:\n logger.info(formatError(authParams.scopes, `Failed to acquire token: ${err.message}`));\n throw err;\n }\n }\n }\n\n let authPromise: Promise<msal.AuthResponse> | undefined;\n if (authResponse === undefined) {\n logger.info(\n `Silent authentication failed, falling back to interactive method ${this.loginStyle}`\n );\n switch (this.loginStyle) {\n case \"redirect\":\n authPromise = new Promise((resolve, reject) => {\n this.msalObject.handleRedirectCallback(resolve, reject);\n });\n this.msalObject.acquireTokenRedirect(authParams);\n break;\n case \"popup\":\n authPromise = this.msalObject.acquireTokenPopup(authParams);\n break;\n }\n\n authResponse = authPromise && (await authPromise);\n }\n\n return authResponse;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span } = createSpan(\"InteractiveBrowserCredential-getToken\", options);\n try {\n if (!this.msalObject.getAccount()) {\n await this.login();\n }\n\n const authResponse = await this.acquireToken({\n scopes: Array.isArray(scopes) ? scopes : scopes.split(\",\")\n });\n\n if (authResponse) {\n const expiresOnTimestamp = authResponse.expiresOn.getTime();\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: authResponse.accessToken,\n expiresOnTimestamp\n };\n } else {\n logger.getToken.info(\"No response\");\n return null;\n }\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n logger.getToken.info(formatError(scopes, err));\n throw err;\n } finally {\n span.end();\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"interactiveBrowserCredential.js","sourceRoot":"","sources":["../../../src/credentials/interactiveBrowserCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAMlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAExE,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAG1E,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,SAAS,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,MAAM,MAAM,GAAG,gBAAgB,CAAC,8BAA8B,CAAC,CAAC;AAEhE;;;;GAIG;AACH,MAAM,OAAO,4BAA4B;IAMvC,YAAY,OAA6C;QACvD,MAAM,QAAQ,GAAG,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,eAAe,CAAC;QAClE,MAAM,QAAQ,GAAG,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,uBAAuB,CAAC;QAE1E,aAAa,CAAC,MAAM,EAA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EAAE,CAAC;gBACV,MAAM,CAAC,CAAC,CAAC,CAAC;YACZ,CAAC,CAAC,CAAC;YAEH,SAAS,OAAO;gBACd,IAAI,MAAM,EAAE;oBACV,MAAM,CAAC,KAAK,EAAE,CAAC;iBAChB;gBAED,KAAK,MAAM,MAAM,IAAI,eAAe,EAAE;oBACpC,MAAM,CAAC,OAAO,EAAE,CAAC;iBAClB;gBAED,IAAI,MAAM,EAAE;oBACV,MAAM,CAAC,KAAK,EAAE,CAAC;oBACf,MAAM,CAAC,IAAI,EAAE,CAAC;iBACf;YACH,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-http\";\nimport { InteractiveBrowserCredentialOptions } from \"./interactiveBrowserCredentialOptions\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { DefaultTenantId, DeveloperSignOnClientId } from \"../constants\";\nimport { Socket } from \"net\";\nimport { AuthenticationRequired, MsalClient } from \"../client/msalClient\";\nimport { AuthorizationCodeRequest } from \"@azure/msal-node\";\n\nimport open from \"open\";\nimport http from \"http\";\nimport stoppable from \"stoppable\";\n\nimport { checkTenantId } from \"../util/checkTenantId\";\n\nconst logger = credentialLogger(\"InteractiveBrowserCredential\");\n\n/**\n * Enables authentication to Azure Active Directory inside of the web browser\n * using the interactive login flow, either via browser redirects or a popup\n * window. This credential is not currently supported in Node.js.\n */\nexport class InteractiveBrowserCredential implements TokenCredential {\n private redirectUri: string;\n private port: number;\n private hostname: string;\n private msalClient: MsalClient;\n\n constructor(options?: InteractiveBrowserCredentialOptions) {\n const tenantId = (options && options.tenantId) || DefaultTenantId;\n const clientId = (options && options.clientId) || DeveloperSignOnClientId;\n\n checkTenantId(logger, tenantId);\n\n // const persistenceEnabled = options?.persistenceEnabled ? options?.persistenceEnabled : false;\n // const authenticationRecord = options?.authenticationRecord;\n\n if (options && options.redirectUri) {\n if (typeof options.redirectUri === \"string\") {\n this.redirectUri = options.redirectUri;\n } else {\n this.redirectUri = options.redirectUri();\n }\n } else {\n this.redirectUri = \"http://localhost\";\n }\n\n const url = new URL(this.redirectUri);\n this.port = parseInt(url.port);\n if (isNaN(this.port)) {\n this.port = 80;\n }\n\n this.hostname = url.hostname;\n\n let authorityHost;\n if (options && options.authorityHost) {\n if (options.authorityHost.endsWith(\"/\")) {\n authorityHost = options.authorityHost + tenantId;\n } else {\n authorityHost = options.authorityHost + \"/\" + tenantId;\n }\n } else {\n authorityHost = \"https://login.microsoftonline.com/\" + tenantId;\n }\n\n this.msalClient = new MsalClient(\n {\n clientId,\n authority: authorityHost,\n knownAuthorities: tenantId === \"adfs\" ? (authorityHost ? [authorityHost] : []) : []\n },\n false,\n undefined,\n options\n );\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public getToken(\n scopes: string | string[],\n _options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const scopeArray = typeof scopes === \"object\" ? scopes : [scopes];\n\n return this.msalClient.acquireTokenFromCache(scopeArray).catch((e) => {\n if (e instanceof AuthenticationRequired) {\n return this.acquireTokenFromBrowser(scopeArray);\n } else {\n logger.getToken.info(formatError(scopes, e));\n throw e;\n }\n });\n }\n\n private async openAuthCodeUrl(scopeArray: string[]): Promise<void> {\n const authCodeUrlParameters = {\n scopes: scopeArray,\n redirectUri: this.redirectUri\n };\n\n const response = await this.msalClient.getAuthCodeUrl(authCodeUrlParameters);\n await open(response);\n }\n\n private acquireTokenFromBrowser(scopeArray: string[]): Promise<AccessToken | null> {\n return new Promise<AccessToken | null>((resolve, reject) => {\n const socketToDestroy: Socket[] = [];\n\n const requestListener = (req: http.IncomingMessage, res: http.ServerResponse) => {\n if (!req.url) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n let url: URL;\n try {\n url = new URL(req.url, this.redirectUri);\n } catch (e) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n const tokenRequest: AuthorizationCodeRequest = {\n code: url.searchParams.get(\"code\")!,\n redirectUri: this.redirectUri,\n scopes: scopeArray\n };\n\n this.msalClient\n .acquireTokenByCode(tokenRequest)\n .then((authResponse) => {\n const successMessage = `Authentication Complete. You can close the browser and return to the application.`;\n if (authResponse && authResponse.expiresOn) {\n const expiresOnTimestamp = authResponse?.expiresOn.valueOf();\n res.writeHead(200);\n res.end(successMessage);\n logger.getToken.info(formatSuccess(scopeArray));\n\n resolve({\n expiresOnTimestamp,\n token: authResponse.accessToken\n });\n } else {\n const errorMessage = formatError(\n scopeArray,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n }\n cleanup();\n return;\n })\n .catch(() => {\n const errorMessage = formatError(\n scopeArray,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n cleanup();\n });\n };\n const app = http.createServer(requestListener);\n\n const listen = app.listen(this.port, this.hostname, () =>\n logger.info(`InteractiveBrowerCredential listening on port ${this.port}!`)\n );\n app.on(\"connection\", (socket) => socketToDestroy.push(socket));\n const server = stoppable(app);\n\n this.openAuthCodeUrl(scopeArray).catch((e) => {\n cleanup();\n reject(e);\n });\n\n function cleanup(): void {\n if (listen) {\n listen.close();\n }\n\n for (const socket of socketToDestroy) {\n socket.destroy();\n }\n\n if (server) {\n server.close();\n server.stop();\n }\n }\n });\n }\n}\n"]}
1
+ {"version":3,"file":"interactiveBrowserCredential.js","sourceRoot":"","sources":["../../../src/credentials/interactiveBrowserCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAMlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAExE,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAG1E,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,SAAS,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,MAAM,MAAM,GAAG,gBAAgB,CAAC,8BAA8B,CAAC,CAAC;AAEhE;;;;GAIG;AACH,MAAM,OAAO,4BAA4B;IAMvC,YAAY,OAA6C;QACvD,MAAM,QAAQ,GAAG,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,eAAe,CAAC;QAClE,MAAM,QAAQ,GAAG,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,uBAAuB,CAAC;QAE1E,aAAa,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAEhC,gGAAgG;QAChG,8DAA8D;QAE9D,IAAI,OAAO,IAAI,OAAO,CAAC,WAAW,EAAE;YAClC,IAAI,OAAO,OAAO,CAAC,WAAW,KAAK,QAAQ,EAAE;gBAC3C,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;aACxC;iBAAM;gBACL,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;aAC1C;SACF;aAA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C;oBACf,MAAM,CAAC,IAAI,EAAE,CAAC;iBACf;YACH,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-auth\";\nimport { InteractiveBrowserCredentialOptions } from \"./interactiveBrowserCredentialOptions\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { DefaultTenantId, DeveloperSignOnClientId } from \"../constants\";\nimport { Socket } from \"net\";\nimport { AuthenticationRequired, MsalClient } from \"../client/msalClient\";\nimport { AuthorizationCodeRequest } from \"@azure/msal-node\";\n\nimport open from \"open\";\nimport http from \"http\";\nimport stoppable from \"stoppable\";\n\nimport { checkTenantId } from \"../util/checkTenantId\";\n\nconst logger = credentialLogger(\"InteractiveBrowserCredential\");\n\n/**\n * Enables authentication to Azure Active Directory inside of the web browser\n * using the interactive login flow, either via browser redirects or a popup\n * window. This credential is not currently supported in Node.js.\n */\nexport class InteractiveBrowserCredential implements TokenCredential {\n private redirectUri: string;\n private port: number;\n private hostname: string;\n private msalClient: MsalClient;\n\n constructor(options?: InteractiveBrowserCredentialOptions) {\n const tenantId = (options && options.tenantId) || DefaultTenantId;\n const clientId = (options && options.clientId) || DeveloperSignOnClientId;\n\n checkTenantId(logger, tenantId);\n\n // const persistenceEnabled = options?.persistenceEnabled ? options?.persistenceEnabled : false;\n // const authenticationRecord = options?.authenticationRecord;\n\n if (options && options.redirectUri) {\n if (typeof options.redirectUri === \"string\") {\n this.redirectUri = options.redirectUri;\n } else {\n this.redirectUri = options.redirectUri();\n }\n } else {\n this.redirectUri = \"http://localhost\";\n }\n\n const url = new URL(this.redirectUri);\n this.port = parseInt(url.port);\n if (isNaN(this.port)) {\n this.port = 80;\n }\n\n this.hostname = url.hostname;\n\n let authorityHost;\n if (options && options.authorityHost) {\n if (options.authorityHost.endsWith(\"/\")) {\n authorityHost = options.authorityHost + tenantId;\n } else {\n authorityHost = options.authorityHost + \"/\" + tenantId;\n }\n } else {\n authorityHost = \"https://login.microsoftonline.com/\" + tenantId;\n }\n\n this.msalClient = new MsalClient(\n {\n clientId,\n authority: authorityHost,\n knownAuthorities: tenantId === \"adfs\" ? (authorityHost ? [authorityHost] : []) : []\n },\n false,\n undefined,\n options\n );\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public getToken(\n scopes: string | string[],\n _options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const scopeArray = typeof scopes === \"object\" ? scopes : [scopes];\n\n return this.msalClient.acquireTokenFromCache(scopeArray).catch((e) => {\n if (e instanceof AuthenticationRequired) {\n return this.acquireTokenFromBrowser(scopeArray);\n } else {\n logger.getToken.info(formatError(scopes, e));\n throw e;\n }\n });\n }\n\n private async openAuthCodeUrl(scopeArray: string[]): Promise<void> {\n const authCodeUrlParameters = {\n scopes: scopeArray,\n redirectUri: this.redirectUri\n };\n\n const response = await this.msalClient.getAuthCodeUrl(authCodeUrlParameters);\n await open(response);\n }\n\n private acquireTokenFromBrowser(scopeArray: string[]): Promise<AccessToken | null> {\n return new Promise<AccessToken | null>((resolve, reject) => {\n const socketToDestroy: Socket[] = [];\n\n const requestListener = (req: http.IncomingMessage, res: http.ServerResponse) => {\n if (!req.url) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n let url: URL;\n try {\n url = new URL(req.url, this.redirectUri);\n } catch (e) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n const tokenRequest: AuthorizationCodeRequest = {\n code: url.searchParams.get(\"code\")!,\n redirectUri: this.redirectUri,\n scopes: scopeArray\n };\n\n this.msalClient\n .acquireTokenByCode(tokenRequest)\n .then((authResponse) => {\n const successMessage = `Authentication Complete. You can close the browser and return to the application.`;\n if (authResponse && authResponse.expiresOn) {\n const expiresOnTimestamp = authResponse?.expiresOn.valueOf();\n res.writeHead(200);\n res.end(successMessage);\n logger.getToken.info(formatSuccess(scopeArray));\n\n resolve({\n expiresOnTimestamp,\n token: authResponse.accessToken\n });\n } else {\n const errorMessage = formatError(\n scopeArray,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n }\n cleanup();\n return;\n })\n .catch(() => {\n const errorMessage = formatError(\n scopeArray,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n cleanup();\n });\n };\n const app = http.createServer(requestListener);\n\n const listen = app.listen(this.port, this.hostname, () =>\n logger.info(`InteractiveBrowerCredential listening on port ${this.port}!`)\n );\n app.on(\"connection\", (socket) => socketToDestroy.push(socket));\n const server = stoppable(app);\n\n this.openAuthCodeUrl(scopeArray).catch((e) => {\n cleanup();\n reject(e);\n });\n\n function cleanup(): void {\n if (listen) {\n listen.close();\n }\n\n for (const socket of socketToDestroy) {\n socket.destroy();\n }\n\n if (server) {\n server.close();\n server.stop();\n }\n }\n });\n }\n}\n"]}
@@ -1,6 +1,8 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT license.
3
3
  import { __awaiter } from "tslib";
4
+ import qs from "qs";
5
+ import { createHttpHeaders } from "@azure/core-rest-pipeline";
4
6
  import { credentialLogger } from "../../util/logging";
5
7
  import { msiGenericGetToken } from "./utils";
6
8
  const logger = credentialLogger("ManagedIdentityCredential - AppServiceMSI 2017");
@@ -17,21 +19,25 @@ function prepareRequestOptions(resource, clientId) {
17
19
  if (clientId) {
18
20
  queryParameters.clientid = clientId;
19
21
  }
22
+ const query = qs.stringify(queryParameters);
20
23
  return {
21
- url: process.env.MSI_ENDPOINT,
24
+ url: `${process.env.MSI_ENDPOINT}?${query}`,
22
25
  method: "GET",
23
- queryParameters,
24
- headers: {
26
+ headers: createHttpHeaders({
25
27
  Accept: "application/json",
26
28
  secret: process.env.MSI_SECRET
27
- }
29
+ })
28
30
  };
29
31
  }
30
32
  export const appServiceMsi2017 = {
31
33
  isAvailable() {
32
34
  return __awaiter(this, void 0, void 0, function* () {
33
35
  const env = process.env;
34
- return Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);
36
+ const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);
37
+ if (!result) {
38
+ logger.info("The Azure App Service MSI 2017 is unavailable.");
39
+ }
40
+ return result;
35
41
  });
36
42
  },
37
43
  getToken(identityClient, resource, clientId, getTokenOptions = {}) {
@@ -1 +1 @@
1
- {"version":3,"file":"appServiceMsi2017.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/appServiceMsi2017.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAIlC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAE7C,MAAM,MAAM,GAAG,gBAAgB,CAAC,gDAAgD,CAAC,CAAC;AAElF,SAAS,eAAe,CAAC,WAAgB;IACvC,4DAA4D;IAC5D,8CAA8C;IAC9C,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,qBAAqB,CAAC,QAAgB,EAAE,QAAiB;IAChE,MAAM,eAAe,GAAQ;QAC3B,QAAQ;QACR,aAAa,EAAE,YAAY;KAC5B,CAAC;IAEF,IAAI,QAAQ,EAAE;QACZ,eAAe,CAAC,QAAQ,GAAG,QAAQ,CAAC;KACrC;IAED,OAAO;QACL,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY;QAC7B,MAAM,EAAE,KAAK;QACb,eAAe;QACf,OAAO,EAAE;YACP,MAAM,EAAE,kBAAkB;YAC1B,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,UAAU;SAC/B;KACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAQ;IAC9B,WAAW;;YACf,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;YACxB,OAAO,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;QACrD,CAAC;KAAA;IACK,QAAQ,CACZ,cAA8B,EAC9B,QAAgB,EAChB,QAAiB,EACjB,kBAAmC,EAAE;;YAErC,MAAM,CAAC,IAAI,CACT,yFAAyF,OAAO,CAAC,GAAG,CAAC,YAAY,6BAA6B,CAC/I,CAAC;YAEF,OAAO,kBAAkB,CACvB,cAAc,EACd,qBAAqB,CAAC,QAAQ,EAAE,QAAQ,CAAC,EACzC,eAAe,EACf,eAAe,CAChB,CAAC;QACJ,CAAC;KAAA;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, RequestPrepareOptions } from \"@azure/core-http\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI } from \"./models\";\nimport { msiGenericGetToken } from \"./utils\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential - AppServiceMSI 2017\");\n\nfunction expiresInParser(requestBody: any): number {\n // Parse a date format like \"06/20/2019 02:57:58 +00:00\" and\n // convert it into a JavaScript-formatted date\n return Date.parse(requestBody.expires_on);\n}\n\nfunction prepareRequestOptions(resource: string, clientId?: string): RequestPrepareOptions {\n const queryParameters: any = {\n resource,\n \"api-version\": \"2017-09-01\"\n };\n\n if (clientId) {\n queryParameters.clientid = clientId;\n }\n\n return {\n url: process.env.MSI_ENDPOINT,\n method: \"GET\",\n queryParameters,\n headers: {\n Accept: \"application/json\",\n secret: process.env.MSI_SECRET\n }\n };\n}\n\nexport const appServiceMsi2017: MSI = {\n async isAvailable(): Promise<boolean> {\n const env = process.env;\n return Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);\n },\n async getToken(\n identityClient: IdentityClient,\n resource: string,\n clientId?: string,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n logger.info(\n `Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`\n );\n\n return msiGenericGetToken(\n identityClient,\n prepareRequestOptions(resource, clientId),\n expiresInParser,\n getTokenOptions\n );\n }\n};\n"]}
1
+ {"version":3,"file":"appServiceMsi2017.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/appServiceMsi2017.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,EAAE,iBAAiB,EAA0B,MAAM,2BAA2B,CAAC;AAGtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAE7C,MAAM,MAAM,GAAG,gBAAgB,CAAC,gDAAgD,CAAC,CAAC;AAElF,SAAS,eAAe,CAAC,WAAgB;IACvC,4DAA4D;IAC5D,8CAA8C;IAC9C,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,qBAAqB,CAAC,QAAgB,EAAE,QAAiB;IAChE,MAAM,eAAe,GAAQ;QAC3B,QAAQ;QACR,aAAa,EAAE,YAAY;KAC5B,CAAC;IAEF,IAAI,QAAQ,EAAE;QACZ,eAAe,CAAC,QAAQ,GAAG,QAAQ,CAAC;KACrC;IAED,MAAM,KAAK,GAAG,EAAE,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IAE5C,OAAO;QACL,GAAG,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,YAAa,IAAI,KAAK,EAAE;QAC5C,MAAM,EAAE,KAAK;QACb,OAAO,EAAE,iBAAiB,CAAC;YACzB,MAAM,EAAE,kBAAkB;YAC1B,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;SAChC,CAAC;KACH,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAQ;IAC9B,WAAW;;YACf,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;YACxB,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;YAC3D,IAAI,CAAC,MAAM,EAAE;gBACX,MAAM,CAAC,IAAI,CAAC,gDAAgD,CAAC,CAAC;aAC/D;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;KAAA;IACK,QAAQ,CACZ,cAA8B,EAC9B,QAAgB,EAChB,QAAiB,EACjB,kBAAmC,EAAE;;YAErC,MAAM,CAAC,IAAI,CACT,yFAAyF,OAAO,CAAC,GAAG,CAAC,YAAY,6BAA6B,CAC/I,CAAC;YAEF,OAAO,kBAAkB,CACvB,cAAc,EACd,qBAAqB,CAAC,QAAQ,EAAE,QAAQ,CAAC,EACzC,eAAe,EACf,eAAe,CAChB,CAAC;QACJ,CAAC;KAAA;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport qs from \"qs\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { createHttpHeaders, PipelineRequestOptions } from \"@azure/core-rest-pipeline\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI } from \"./models\";\nimport { msiGenericGetToken } from \"./utils\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential - AppServiceMSI 2017\");\n\nfunction expiresInParser(requestBody: any): number {\n // Parse a date format like \"06/20/2019 02:57:58 +00:00\" and\n // convert it into a JavaScript-formatted date\n return Date.parse(requestBody.expires_on);\n}\n\nfunction prepareRequestOptions(resource: string, clientId?: string): PipelineRequestOptions {\n const queryParameters: any = {\n resource,\n \"api-version\": \"2017-09-01\"\n };\n\n if (clientId) {\n queryParameters.clientid = clientId;\n }\n\n const query = qs.stringify(queryParameters);\n\n return {\n url: `${process.env.MSI_ENDPOINT!}?${query}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n secret: process.env.MSI_SECRET!\n })\n };\n}\n\nexport const appServiceMsi2017: MSI = {\n async isAvailable(): Promise<boolean> {\n const env = process.env;\n const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);\n if (!result) {\n logger.info(\"The Azure App Service MSI 2017 is unavailable.\");\n }\n return result;\n },\n async getToken(\n identityClient: IdentityClient,\n resource: string,\n clientId?: string,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n logger.info(\n `Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`\n );\n\n return msiGenericGetToken(\n identityClient,\n prepareRequestOptions(resource, clientId),\n expiresInParser,\n getTokenOptions\n );\n }\n};\n"]}
@@ -1,6 +1,8 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT license.
3
3
  import { __awaiter } from "tslib";
4
+ import qs from "qs";
5
+ import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline";
4
6
  import { credentialLogger } from "../../util/logging";
5
7
  import { msiGenericGetToken } from "./utils";
6
8
  import { azureArcAPIVersion } from "./constants";
@@ -14,15 +16,15 @@ function prepareRequestOptions(resource) {
14
16
  resource,
15
17
  "api-version": azureArcAPIVersion
16
18
  };
19
+ const query = qs.stringify(queryParameters);
17
20
  return {
18
21
  // Should be similar to: http://localhost:40342/metadata/identity/oauth2/token
19
- url: process.env.IDENTITY_ENDPOINT,
22
+ url: `${process.env.IDENTITY_ENDPOINT}?${query}`,
20
23
  method: "GET",
21
- queryParameters,
22
- headers: {
24
+ headers: createHttpHeaders({
23
25
  Accept: "application/json",
24
- Metadata: true
25
- }
26
+ Metadata: "true"
27
+ })
26
28
  };
27
29
  }
28
30
  // Since "fs"'s readFileSync locks the thread, and to avoid extra dependencies.
@@ -36,7 +38,7 @@ function readFileAsync(path, options) {
36
38
  }
37
39
  function filePathRequest(identityClient, requestPrepareOptions) {
38
40
  return __awaiter(this, void 0, void 0, function* () {
39
- const response = yield identityClient.sendRequest(identityClient.createWebResource(requestPrepareOptions));
41
+ const response = yield identityClient.sendRequest(createPipelineRequest(requestPrepareOptions));
40
42
  if (response.status !== 401) {
41
43
  let message = "";
42
44
  if (response.bodyAsText) {
@@ -51,22 +53,27 @@ function filePathRequest(identityClient, requestPrepareOptions) {
51
53
  export const arcMsi = {
52
54
  isAvailable() {
53
55
  return __awaiter(this, void 0, void 0, function* () {
54
- return Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);
56
+ const result = Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);
57
+ if (!result) {
58
+ logger.info("The Azure Arc MSI is unavailable.");
59
+ }
60
+ return result;
55
61
  });
56
62
  },
57
63
  getToken(identityClient, resource, clientId, getTokenOptions = {}) {
64
+ var _a;
58
65
  return __awaiter(this, void 0, void 0, function* () {
59
66
  logger.info(`Using the Azure Arc MSI to authenticate.`);
60
67
  if (clientId) {
61
68
  throw new Error("User assigned identity is not supported by the Azure Arc Managed Identity Endpoint. To authenticate with the system assigned identity omit the client id when constructing the ManagedIdentityCredential, or if authenticating with the DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set.");
62
69
  }
63
- const requestOptions = Object.assign({ disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal, spanOptions: getTokenOptions.tracingOptions && getTokenOptions.tracingOptions.spanOptions, tracingContext: getTokenOptions.tracingOptions && getTokenOptions.tracingOptions.tracingContext }, prepareRequestOptions(resource));
70
+ const requestOptions = Object.assign({ allowInsecureConnection: true, disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal, spanOptions: getTokenOptions.tracingOptions && getTokenOptions.tracingOptions.spanOptions }, prepareRequestOptions(resource));
64
71
  const filePath = yield filePathRequest(identityClient, requestOptions);
65
72
  if (!filePath) {
66
73
  throw new Error("Azure Arc MSI failed to find the token file.");
67
74
  }
68
75
  const key = yield readFileAsync(filePath, { encoding: "utf-8" });
69
- requestOptions.headers["Authorization"] = `Basic ${key}`;
76
+ (_a = requestOptions.headers) === null || _a === void 0 ? void 0 : _a.set("Authorization", `Basic ${key}`);
70
77
  return msiGenericGetToken(identityClient, requestOptions, expiresInParser, getTokenOptions);
71
78
  });
72
79
  }
@@ -1 +1 @@
1
- {"version":3,"file":"arcMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/arcMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAIlC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,gBAAgB,CAAC,oCAAoC,CAAC,CAAC;AAEtE,yDAAyD;AACzD,MAAM,eAAe,GAAG,SAAS,CAAC;AAElC,SAAS,qBAAqB,CAAC,QAAiB;IAC9C,MAAM,eAAe,GAAQ;QAC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from \"@azure/core-http\";\nimport { MSI } from \"./models\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { msiGenericGetToken } from \"./utils\";\nimport { azureArcAPIVersion } from \"./constants\";\nimport { AuthenticationError } from \"../../client/errors\";\nimport { readFile } from \"fs\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential - ArcMSI\");\n\n// Azure Arc MSI doesn't have a special expiresIn parser.\nconst expiresInParser = undefined;\n\nfunction prepareRequestOptions(resource?: string): RequestPrepareOptions {\n const queryParameters: any = {\n resource,\n \"api-version\": azureArcAPIVersion\n };\n\n return {\n // Should be similar to: http://localhost:40342/metadata/identity/oauth2/token\n url: process.env.IDENTITY_ENDPOINT,\n method: \"GET\",\n queryParameters,\n headers: {\n Accept: \"application/json\",\n Metadata: true\n }\n };\n}\n\n// Since \"fs\"'s readFileSync locks the thread, and to avoid extra dependencies.\nfunction readFileAsync(path: string, options: { encoding: string }): Promise<string> {\n return new Promise((resolve, reject) =>\n readFile(path, options, (err, data) => {\n if (err) {\n reject(err);\n }\n resolve(data);\n })\n );\n}\n\nasync function filePathRequest(\n identityClient: IdentityClient,\n requestPrepareOptions: RequestPrepareOptions\n): Promise<string | undefined> {\n const response = await identityClient.sendRequest(\n identityClient.createWebResource(requestPrepareOptions)\n );\n\n if (response.status !== 401) {\n let message = \"\";\n if (response.bodyAsText) {\n message = ` Response: ${response.bodyAsText}`;\n }\n throw new AuthenticationError(\n response.status,\n `To authenticate with Azure Arc MSI, status code 401 is expected on the first request.${message}`\n );\n }\n\n const authHeader = response.headers.get(\"www-authenticate\") || \"\";\n return authHeader.split(\"=\").slice(1)[0];\n}\n\nexport const arcMsi: MSI = {\n async isAvailable(): Promise<boolean> {\n return Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);\n },\n async getToken(\n identityClient: IdentityClient,\n resource?: string,\n clientId?: string,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n logger.info(`Using the Azure Arc MSI to authenticate.`);\n\n if (clientId) {\n throw new Error(\n \"User assigned identity is not supported by the Azure Arc Managed Identity Endpoint. To authenticate with the system assigned identity omit the client id when constructing the ManagedIdentityCredential, or if authenticating with the DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set.\"\n );\n }\n\n const requestOptions = {\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n abortSignal: getTokenOptions.abortSignal,\n spanOptions: getTokenOptions.tracingOptions && getTokenOptions.tracingOptions.spanOptions,\n tracingContext: getTokenOptions.tracingOptions && getTokenOptions.tracingOptions.tracingContext,\n ...prepareRequestOptions(resource)\n };\n\n const filePath = await filePathRequest(identityClient, requestOptions);\n\n if (!filePath) {\n throw new Error(\"Azure Arc MSI failed to find the token file.\");\n }\n\n const key = await readFileAsync(filePath, { encoding: \"utf-8\" });\n requestOptions.headers![\"Authorization\"] = `Basic ${key}`;\n\n return msiGenericGetToken(identityClient, requestOptions, expiresInParser, getTokenOptions);\n }\n};\n"]}
1
+ {"version":3,"file":"arcMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/arcMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EAEtB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,gBAAgB,CAAC,oCAAoC,CAAC,CAAC;AAEtE,yDAAyD;AACzD,MAAM,eAAe,GAAG,SAAS,CAAC;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,CAAC,eAAe,EAAE,SAAS,GAAG,EAAE,EAAE;YAE7D,OAAO,kBAAkB,CAAC,cAAc,EAAE,cAAc,EAAE,eAAe,EAAE,eAAe,CAAC,CAAC;;KAC7F;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport qs from \"qs\";\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequestOptions\n} from \"@azure/core-rest-pipeline\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI } from \"./models\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { msiGenericGetToken } from \"./utils\";\nimport { azureArcAPIVersion } from \"./constants\";\nimport { AuthenticationError } from \"../../client/errors\";\nimport { readFile } from \"fs\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential - ArcMSI\");\n\n// Azure Arc MSI doesn't have a special expiresIn parser.\nconst expiresInParser = undefined;\n\nfunction prepareRequestOptions(resource?: string): PipelineRequestOptions {\n const queryParameters: any = {\n resource,\n \"api-version\": azureArcAPIVersion\n };\n\n const query = qs.stringify(queryParameters);\n\n return {\n // Should be similar to: http://localhost:40342/metadata/identity/oauth2/token\n url: `${process.env.IDENTITY_ENDPOINT!}?${query}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n Metadata: \"true\"\n })\n };\n}\n\n// Since \"fs\"'s readFileSync locks the thread, and to avoid extra dependencies.\nfunction readFileAsync(path: string, options: { encoding: string }): Promise<string> {\n return new Promise((resolve, reject) =>\n readFile(path, options, (err, data) => {\n if (err) {\n reject(err);\n }\n resolve(data);\n })\n );\n}\n\nasync function filePathRequest(\n identityClient: IdentityClient,\n requestPrepareOptions: PipelineRequestOptions\n): Promise<string | undefined> {\n const response = await identityClient.sendRequest(createPipelineRequest(requestPrepareOptions));\n\n if (response.status !== 401) {\n let message = \"\";\n if (response.bodyAsText) {\n message = ` Response: ${response.bodyAsText}`;\n }\n throw new AuthenticationError(\n response.status,\n `To authenticate with Azure Arc MSI, status code 401 is expected on the first request.${message}`\n );\n }\n\n const authHeader = response.headers.get(\"www-authenticate\") || \"\";\n return authHeader.split(\"=\").slice(1)[0];\n}\n\nexport const arcMsi: MSI = {\n async isAvailable(): Promise<boolean> {\n const result = Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);\n if (!result) {\n logger.info(\"The Azure Arc MSI is unavailable.\");\n }\n return result;\n },\n async getToken(\n identityClient: IdentityClient,\n resource?: string,\n clientId?: string,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n logger.info(`Using the Azure Arc MSI to authenticate.`);\n\n if (clientId) {\n throw new Error(\n \"User assigned identity is not supported by the Azure Arc Managed Identity Endpoint. To authenticate with the system assigned identity omit the client id when constructing the ManagedIdentityCredential, or if authenticating with the DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set.\"\n );\n }\n\n const requestOptions = {\n allowInsecureConnection: true,\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n abortSignal: getTokenOptions.abortSignal,\n spanOptions: getTokenOptions.tracingOptions && getTokenOptions.tracingOptions.spanOptions,\n ...prepareRequestOptions(resource)\n };\n\n const filePath = await filePathRequest(identityClient, requestOptions);\n\n if (!filePath) {\n throw new Error(\"Azure Arc MSI failed to find the token file.\");\n }\n\n const key = await readFileAsync(filePath, { encoding: \"utf-8\" });\n requestOptions.headers?.set(\"Authorization\", `Basic ${key}`);\n\n return msiGenericGetToken(identityClient, requestOptions, expiresInParser, getTokenOptions);\n }\n};\n"]}