UNPKG

@azure/identity

Version:

Provides credential implementations for Azure SDK libraries that can authenticate with Microsoft Entra ID

177 lines (176 loc) • 7.21 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var onBehalfOfCredential_exports = {}; __export(onBehalfOfCredential_exports, { OnBehalfOfCredential: () => OnBehalfOfCredential }); module.exports = __toCommonJS(onBehalfOfCredential_exports); var import_msalClient = require("../msal/nodeFlows/msalClient.js"); var import_logging = require("../util/logging.js"); var import_tenantIdUtils = require("../util/tenantIdUtils.js"); var import_errors = require("../errors.js"); var import_node_crypto = require("node:crypto"); var import_scopeUtils = require("../util/scopeUtils.js"); var import_promises = require("node:fs/promises"); var import_tracing = require("../util/tracing.js"); const credentialName = "OnBehalfOfCredential"; const logger = (0, import_logging.credentialLogger)(credentialName); class OnBehalfOfCredential { tenantId; additionallyAllowedTenantIds; msalClient; sendCertificateChain; certificatePath; clientSecret; userAssertionToken; clientAssertion; constructor(options) { const { clientSecret } = options; const { certificatePath, sendCertificateChain } = options; const { getAssertion } = options; const { tenantId, clientId, userAssertionToken, additionallyAllowedTenants: additionallyAllowedTenantIds } = options; if (!tenantId) { throw new import_errors.CredentialUnavailableError( `${credentialName}: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.` ); } if (!clientId) { throw new import_errors.CredentialUnavailableError( `${credentialName}: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.` ); } if (!clientSecret && !certificatePath && !getAssertion) { throw new import_errors.CredentialUnavailableError( `${credentialName}: You must provide one of clientSecret, certificatePath, or a getAssertion callback but none were provided. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.` ); } if (!userAssertionToken) { throw new import_errors.CredentialUnavailableError( `${credentialName}: userAssertionToken is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.` ); } this.certificatePath = certificatePath; this.clientSecret = clientSecret; this.userAssertionToken = userAssertionToken; this.sendCertificateChain = sendCertificateChain; this.clientAssertion = getAssertion; this.tenantId = tenantId; this.additionallyAllowedTenantIds = (0, import_tenantIdUtils.resolveAdditionallyAllowedTenantIds)( additionallyAllowedTenantIds ); this.msalClient = (0, import_msalClient.createMsalClient)(clientId, this.tenantId, { ...options, logger, tokenCredentialOptions: options }); } /** * Authenticates with Microsoft Entra ID and returns an access token if successful. * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. * * @param scopes - The list of scopes for which the token will have access. * @param options - The options used to configure the underlying network requests. */ async getToken(scopes, options = {}) { return import_tracing.tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => { newOptions.tenantId = (0, import_tenantIdUtils.processMultiTenantRequest)( this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger ); const arrayScopes = (0, import_scopeUtils.ensureScopes)(scopes); if (this.certificatePath) { const clientCertificate = await this.buildClientCertificate(this.certificatePath); return this.msalClient.getTokenOnBehalfOf( arrayScopes, this.userAssertionToken, clientCertificate, newOptions ); } else if (this.clientSecret) { return this.msalClient.getTokenOnBehalfOf( arrayScopes, this.userAssertionToken, this.clientSecret, options ); } else if (this.clientAssertion) { return this.msalClient.getTokenOnBehalfOf( arrayScopes, this.userAssertionToken, this.clientAssertion, options ); } else { throw new Error( "Expected either clientSecret or certificatePath or clientAssertion to be defined." ); } }); } async buildClientCertificate(certificatePath) { try { const parts = await this.parseCertificate({ certificatePath }, this.sendCertificateChain); return { thumbprint: parts.thumbprint, thumbprintSha256: parts.thumbprintSha256, privateKey: parts.certificateContents, x5c: parts.x5c }; } catch (error) { logger.info((0, import_logging.formatError)("", error)); throw error; } } async parseCertificate(configuration, sendCertificateChain) { const certificatePath = configuration.certificatePath; const certificateContents = await (0, import_promises.readFile)(certificatePath, "utf8"); const x5c = sendCertificateChain ? certificateContents : void 0; const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g; const publicKeys = []; let match; do { match = certificatePattern.exec(certificateContents); if (match) { publicKeys.push(match[3]); } } while (match); if (publicKeys.length === 0) { throw new Error("The file at the specified path does not contain a PEM-encoded certificate."); } const thumbprint = (0, import_node_crypto.createHash)("sha1").update(Buffer.from(publicKeys[0], "base64")).digest("hex").toUpperCase(); const thumbprintSha256 = (0, import_node_crypto.createHash)("sha256").update(Buffer.from(publicKeys[0], "base64")).digest("hex").toUpperCase(); return { certificateContents, thumbprintSha256, thumbprint, x5c }; } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { OnBehalfOfCredential }); //# sourceMappingURL=onBehalfOfCredential.js.map