applicationTokenCertificateCredentials.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Licensed under the MIT License. See License.txt in the project root for license information.
  3. import { readFileSync } from "fs";
  4. import { createHash } from "crypto";
  5. import { ApplicationTokenCredentialsBase } from "./applicationTokenCredentialsBase";
  6. import { Environment } from "@azure/ms-rest-azure-env";
  7. import { AuthConstants, TokenAudience } from "../util/authConstants";
  8. import { TokenResponse, ErrorResponse, TokenCache } from "adal-node";
  9. import { AzureTokenCredentialsOptions } from "../login";
  10. export class ApplicationTokenCertificateCredentials extends ApplicationTokenCredentialsBase {
  11. readonly certificate: string;
  12. readonly thumbprint: string;
  13. /**
  14. * Creates a new ApplicationTokenCredentials object.
  15. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  16. * for detailed instructions on creating an Azure Active Directory application.
  17. * @constructor
  18. * @param {string} clientId The active directory application client id.
  19. * @param {string} domain The domain or tenant id containing this application.
  20. * @param {string} certificate A PEM encoded certificate private key.
  21. * @param {string} thumbprint A hex encoded thumbprint of the certificate.
  22. * @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/'.
  23. * 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).
  24. * @param {Environment} [environment] The azure environment to authenticate with.
  25. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  26. */
  27. public constructor(
  28. clientId: string,
  29. domain: string,
  30. certificate: string,
  31. thumbprint: string,
  32. tokenAudience?: TokenAudience,
  33. environment?: Environment,
  34. tokenCache?: TokenCache
  35. ) {
  36. if (!certificate || typeof certificate.valueOf() !== "string") {
  37. throw new Error("certificate must be a non empty string.");
  38. }
  39. if (!thumbprint || typeof thumbprint.valueOf() !== "string") {
  40. throw new Error("thumbprint must be a non empty string.");
  41. }
  42. super(clientId, domain, tokenAudience, environment, tokenCache);
  43. this.certificate = certificate;
  44. this.thumbprint = thumbprint;
  45. }
  46. /**
  47. * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
  48. * @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
  49. */
  50. public async getToken(): Promise<TokenResponse> {
  51. try {
  52. const tokenResponse = await this.getTokenFromCache();
  53. return tokenResponse;
  54. } catch (error) {
  55. if (error.message.startsWith(AuthConstants.SDK_INTERNAL_ERROR)) {
  56. return Promise.reject(error);
  57. }
  58. return new Promise((resolve, reject) => {
  59. const resource = this.getActiveDirectoryResourceId();
  60. this.authContext.acquireTokenWithClientCertificate(
  61. resource,
  62. this.clientId,
  63. this.certificate,
  64. this.thumbprint,
  65. (error: any, tokenResponse: TokenResponse | ErrorResponse) => {
  66. if (error) {
  67. return reject(error);
  68. }
  69. if (tokenResponse.error || tokenResponse.errorDescription) {
  70. return reject(tokenResponse);
  71. }
  72. return resolve(tokenResponse as TokenResponse);
  73. }
  74. );
  75. });
  76. }
  77. }
  78. /**
  79. * Creates a new instance of ApplicationTokenCertificateCredentials.
  80. *
  81. * @param clientId The active directory application client id also known as the SPN (ServicePrincipal Name).
  82. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  83. * for an example.
  84. * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example:
  85. * - CertificateString: "-----BEGIN PRIVATE KEY-----\n<xxxxx>\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n<yyyyy>\n-----END CERTIFICATE-----\n"
  86. * - CertificateFilePath: **Absolute** file path of the .pem file.
  87. * @param domain The domain or tenant id containing this application.
  88. * @param options AzureTokenCredentialsOptions - Object representing optional parameters.
  89. *
  90. * @returns ApplicationTokenCertificateCredentials
  91. */
  92. public static create(
  93. clientId: string,
  94. certificateStringOrFilePath: string,
  95. domain: string,
  96. options: AzureTokenCredentialsOptions
  97. ): ApplicationTokenCertificateCredentials {
  98. if (
  99. !certificateStringOrFilePath ||
  100. typeof certificateStringOrFilePath.valueOf() !== "string"
  101. ) {
  102. throw new Error(
  103. "'certificateStringOrFilePath' must be a non empty string."
  104. );
  105. }
  106. if (!certificateStringOrFilePath.startsWith("-----BEGIN")) {
  107. certificateStringOrFilePath = readFileSync(
  108. certificateStringOrFilePath,
  109. "utf8"
  110. );
  111. }
  112. const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9\+\/\n\r]+\=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/;
  113. const matchCert = certificateStringOrFilePath.match(certificatePattern);
  114. const rawCertificate = matchCert ? matchCert[3] : "";
  115. if (!rawCertificate) {
  116. throw new Error(
  117. "Unable to correctly parse the certificate from the value provided in 'certificateStringOrFilePath' "
  118. );
  119. }
  120. const thumbprint = createHash("sha1")
  121. .update(Buffer.from(rawCertificate, "base64"))
  122. .digest("hex");
  123. return new ApplicationTokenCertificateCredentials(
  124. clientId,
  125. domain,
  126. certificateStringOrFilePath,
  127. thumbprint,
  128. options.tokenAudience,
  129. options.environment,
  130. options.tokenCache
  131. );
  132. }
  133. }