Use clientCredentials with msal-node

Viewed 498

I've got an on-prem nodejs SPA that I want to secure with MSAL. The Node sample project uses msal-node with this config and it authenticates correctly.

const config = {
    auth: {
        clientId: "025BlahBlahBlahb3ac",
        authority: "https://login.microsoftonline.com/04ccTenantIDdbdaf",
        clientSecret: "-6csBlahBlahBlahsqO"
    }

However, the tutorial states "Use certificate credentials instead of client secrets in your confidential client applications"

Which, I think, means the config should look like

const config = {
    auth: {
        clientId: "025BlahBlahBlahb3ac",
        authority: "https://login.microsoftonline.com/04ccTenantIDdbdaf",
        clientCertificate: {
            thumbprint: string;
            privateKey: string;
        }
    };

I've created a certificate in Azure KeyVault (with no secrets yet) and exported the pem, which gives me a private key and certificate. Am I using a jwt plugin or just filling in the thumbprint and privateKey?

The start of the private key in the pem looks like this

-----BEGIN PRIVATE KEY-----
BIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCfGkz5bHZe1g5K
zQXDNHd7RecP+/TgN/4rQdyBeSnNhijyT1cG93cglo9Bg9eAeFMvO8AONNyucdpV

Is this an fs.readFileSync or is there some encoding to do for the key?

2 Answers

Amazing how easy it can be after a night's rest.

  1. Create a PEM certificate in the Azure KeyVault
  2. Export both CER and PEM formats.
  3. Import the CER into the App Registration (I deleted my client secret)
  4. Place the PEM in the app directory.
const express = require("express");
const msal = require('@azure/msal-node');
const fs = require('fs');

const PRIV_KEY = fs.readFileSync(__dirname + '/lf-kv-ae-int-LF-CERT-INT-KV-20210610.pem', 'utf8');

const SERVER_PORT = process.env.PORT || 3000;
const REDIRECT_URI = "http://localhost:3000/redirect";

const config = {
    auth: {
        clientId: "025dfgq28-AppRegistrationClientID-8d50ert5b3ac",
        authority: "https://login.microsoftonline.com/04ccwra3-YourTenantID-5ewe6u8uaf",
        clientCertificate: {
            thumbprint: "7CA7CopyTheThumbprintFromTheCertificateE8E",
            privateKey: PRIV_KEY
        }
    },
    system: {
        loggerOptions: {
            loggerCallback(loglevel, message, containsPii) {
                console.log(message);
            },
            piiLoggingEnabled: false,
            logLevel: msal.LogLevel.Verbose,
        }
    }
};

// Create msal application object
const pca = new msal.ConfidentialClientApplication(config);
// The rest of the code is in the example...

The content of PEM file you shared is your cert private key, if you want to use it to get access tokens from Azure AD by node js just try Step 3 in my previous post here: just specify your .pem file path in code.

Let me know if you have any more questions.

Related