Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

591
Views
azure active directory obtenga token de acceso usando SPN con certificado en msal-node js frente al error "ERR_OSSL_PEM_NO_START_LINE"

Estoy tratando de obtener el token de acceso de Azure usando el nodo msal y necesito seguir el principio de servicio con el certificado. Actualmente estoy usando la URL de la bóveda de claves para leer el certificado. Mi documento de referencias es https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/samples/msal-node-samples/auth-code-key-vault/index.js

 const msal = require('@azure/msal-node'); const { DefaultAzureCredential } = require('@azure/identity'); const { CertificateClient } = require('@azure/keyvault-certificates'); const { SecretClient } = require('@azure/keyvault-secrets'); const getazureToken = async () => { const credential = new DefaultAzureCredential(); const client = new CertificateClient(config.keyVaultUrl, credential); const secretClient = new SecretClient(config.keyVaultUrl, credential); const certResponse = await client.getCertificate(config.certificateName); const thumbprint = certResponse.properties.x509Thumbprint.toString('hex'); const secretResponse = await secretClient.getSecret(config.certificateName); const privateKey = secretResponse.value; await msalApp(thumbprint, privateKey); }; async function msalApp(thumbprint, privateKey) { // Before running the sample, you will need to replace the values in the config const msalConfig = { auth: { clientId: config.azureClientId, authority: `${config.authorityUri}${config.tenantId}/`, clientCertificate: { thumbprint, privateKey, }, }, system: { loggerOptions: { loggerCallback(loglevel, message, containsPii) { console.log('loglevel', loglevel, message); }, piiLoggingEnabled: false, logLevel: msal.LogLevel.Verbose, }, }, }; // Create msal application object const cca = new msal.ConfidentialClientApplication(msalConfig); const authCodeUrlParameters = { scopes: config.scope, }; cca .acquireTokenByClientCredential(authCodeUrlParameters) .then((response) => { console.log('==========> response', response); }) .catch((error) => console.log('error------------->', JSON.stringify(error)) ); }

error: ingrese la descripción de la imagen aquí

También tengo un archivo .pfx de certificado. Si puede ser útil.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

soluciones es que puede extraer archivos .pem del archivo .pfx del certificado usando el siguiente código

 const forge = require('node-forge'); const fs = require('fs'); const convertPfxToPem = async (keyFile, passphrase) => { const keyBase64 = keyFile.toString('base64'); const p12Der = forge.util.decode64(keyBase64); const asn = forge.asn1.fromDer(p12Der); const p12 = forge.pkcs12.pkcs12FromAsn1(asn, false, passphrase); // Retrieve key data const keyData = p12 .getBags({ bagType: forge.pki.oids.pkcs8ShroudedKeyBag }) [forge.pki.oids.pkcs8ShroudedKeyBag].concat( p12.getBags({ bagType: forge.pki.oids.keyBag })[forge.pki.oids.keyBag] ); // Convert a Forge private key to an ASN.1 RSAPrivateKey const rsaPrivateKey = forge.pki.privateKeyToAsn1(keyData[0].key); // Wrap an RSAPrivateKey ASN.1 object in a PKCS#8 ASN.1 PrivateKeyInfo const privateKeyInfo = forge.pki.wrapRsaPrivateKey(rsaPrivateKey); // Convert a PKCS#8 ASN.1 PrivateKeyInfo to PEM const privateKey = forge.pki.privateKeyInfoToPem(privateKeyInfo); fs.writeFileSync('key.pem', privateKey); return { key: privateKey, }; };

ahora lea el archivo .pfx y almacene key.pem y utilícelo.

 let key = null; if (fs.existsSync(path.resolve(__dirname, '../key.pem'))) { key = fs.readFileSync(path.resolve(__dirname, '../key.pem')); } else { const pemResponse = await convertPfxToPem( fs.readFileSync(path.resolve(__dirname, '../certificate.pfx')), config.passphrase ); key = pemResponse.key; }

y getazureToken se ven como a continuación

 const credential = new DefaultAzureCredential(); const client = new CertificateClient(config.keyVaultUrl, credential); const certResponse = await client.getCertificate(config.certificateName); const thumbprint = certResponse.properties.x509Thumbprint.toString('hex'); let key = null; if (fs.existsSync(path.resolve(__dirname, '../key.pem'))) { key = fs.readFileSync(path.resolve(__dirname, '../key.pem')); } else { const pemResponse = await convertPfxToPem( fs.readFileSync(path.resolve(__dirname, '../certificate.pfx')), config.passphrase ); key = pemResponse.key; } try { const tokenResponse = await msalApp(thumbprint, key); return tokenResponse; } catch (err) {}
about 4 years ago · Juan Pablo Isaza Report

0

Este error puede ocurrir cuando el certificado que intentamos cargar en formato pem no tiene el formato correcto.

Verifique el formato de sus certificados en el archivo Pem.js. Confirme si el contenido del archivo pem es decir; La cadena del certificado y la cadena de la clave privada tienen el siguiente formato: Esto implica rodear la clave con líneas, incluidos 5 guiones antes y después de BEGIN / END CERTIFICATE y cada uno en una línea diferente. Algo como abajo

-----COMENZAR CLAVE PRIVADA-----\nCADENA_LARGA_AQUÍ\n-----FIN CLAVE PRIVADA-----

(Verifique si se perdió alguno de los caracteres o guiones) Puede verificar su certificado aquí Y luego intente eliminar (espacios en blanco), es decir; "\s" después y antes de BEGIN / END CERTIFICATE y reemplazándolos con una nueva línea "\n" tanto de la expresión regular del certificado como de la expresión regular de la clave privada del archivo pem.js con la ayuda de las funciones involucradas o modifíquelas manualmente en consecuencia.

Consulte también https://github.com/auth0/node-jsonwebtoken/issues/642#issuecomment .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!