applicationTokenCertificateCredentials.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. "use strict";
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. // Licensed under the MIT License. See License.txt in the project root for license information.
  4. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5. return new (P || (P = Promise))(function (resolve, reject) {
  6. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  7. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  8. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  9. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10. });
  11. };
  12. Object.defineProperty(exports, "__esModule", { value: true });
  13. const fs_1 = require("fs");
  14. const crypto_1 = require("crypto");
  15. const applicationTokenCredentialsBase_1 = require("./applicationTokenCredentialsBase");
  16. const authConstants_1 = require("../util/authConstants");
  17. class ApplicationTokenCertificateCredentials extends applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase {
  18. /**
  19. * Creates a new ApplicationTokenCredentials object.
  20. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  21. * for detailed instructions on creating an Azure Active Directory application.
  22. * @constructor
  23. * @param {string} clientId The active directory application client id.
  24. * @param {string} domain The domain or tenant id containing this application.
  25. * @param {string} certificate A PEM encoded certificate private key.
  26. * @param {string} thumbprint A hex encoded thumbprint of the certificate.
  27. * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  28. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  29. * @param {Environment} [environment] The azure environment to authenticate with.
  30. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  31. */
  32. constructor(clientId, domain, certificate, thumbprint, tokenAudience, environment, tokenCache) {
  33. if (!certificate || typeof certificate.valueOf() !== "string") {
  34. throw new Error("certificate must be a non empty string.");
  35. }
  36. if (!thumbprint || typeof thumbprint.valueOf() !== "string") {
  37. throw new Error("thumbprint must be a non empty string.");
  38. }
  39. super(clientId, domain, tokenAudience, environment, tokenCache);
  40. this.certificate = certificate;
  41. this.thumbprint = thumbprint;
  42. }
  43. /**
  44. * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
  45. * @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
  46. */
  47. getToken() {
  48. return __awaiter(this, void 0, void 0, function* () {
  49. try {
  50. const tokenResponse = yield this.getTokenFromCache();
  51. return tokenResponse;
  52. }
  53. catch (error) {
  54. if (error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) {
  55. return Promise.reject(error);
  56. }
  57. return new Promise((resolve, reject) => {
  58. const resource = this.getActiveDirectoryResourceId();
  59. this.authContext.acquireTokenWithClientCertificate(resource, this.clientId, this.certificate, this.thumbprint, (error, tokenResponse) => {
  60. if (error) {
  61. return reject(error);
  62. }
  63. if (tokenResponse.error || tokenResponse.errorDescription) {
  64. return reject(tokenResponse);
  65. }
  66. return resolve(tokenResponse);
  67. });
  68. });
  69. }
  70. });
  71. }
  72. /**
  73. * Creates a new instance of ApplicationTokenCertificateCredentials.
  74. *
  75. * @param clientId The active directory application client id also known as the SPN (ServicePrincipal Name).
  76. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  77. * for an example.
  78. * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example:
  79. * - CertificateString: "-----BEGIN PRIVATE KEY-----\n<xxxxx>\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n<yyyyy>\n-----END CERTIFICATE-----\n"
  80. * - CertificateFilePath: **Absolute** file path of the .pem file.
  81. * @param domain The domain or tenant id containing this application.
  82. * @param options AzureTokenCredentialsOptions - Object representing optional parameters.
  83. *
  84. * @returns ApplicationTokenCertificateCredentials
  85. */
  86. static create(clientId, certificateStringOrFilePath, domain, options) {
  87. if (!certificateStringOrFilePath ||
  88. typeof certificateStringOrFilePath.valueOf() !== "string") {
  89. throw new Error("'certificateStringOrFilePath' must be a non empty string.");
  90. }
  91. if (!certificateStringOrFilePath.startsWith("-----BEGIN")) {
  92. certificateStringOrFilePath = fs_1.readFileSync(certificateStringOrFilePath, "utf8");
  93. }
  94. const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9\+\/\n\r]+\=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/;
  95. const matchCert = certificateStringOrFilePath.match(certificatePattern);
  96. const rawCertificate = matchCert ? matchCert[3] : "";
  97. if (!rawCertificate) {
  98. throw new Error("Unable to correctly parse the certificate from the value provided in 'certificateStringOrFilePath' ");
  99. }
  100. const thumbprint = crypto_1.createHash("sha1")
  101. .update(Buffer.from(rawCertificate, "base64"))
  102. .digest("hex");
  103. return new ApplicationTokenCertificateCredentials(clientId, domain, certificateStringOrFilePath, thumbprint, options.tokenAudience, options.environment, options.tokenCache);
  104. }
  105. }
  106. exports.ApplicationTokenCertificateCredentials = ApplicationTokenCertificateCredentials;
  107. //# sourceMappingURL=applicationTokenCertificateCredentials.js.map