Skip to content

Instantly share code, notes, and snippets.

@wattry
Created December 23, 2021 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wattry/d18a66b8e6bb15436b1ba0246021de15 to your computer and use it in GitHub Desktop.
Save wattry/d18a66b8e6bb15436b1ba0246021de15 to your computer and use it in GitHub Desktop.
Bare bones implementation of an ldapts client and binds using SASL
import fs from 'fs';
import ldapts from 'ldapts';
import AWS from 'aws-sdk';
import fs from 'fs';
const LDAP_HOST_CONST = "ldaps://my.ldap.server.com";
// You chose your flavor for fetching secrets, this covers from disk or AWS secret manager.
async function bindFromFile(): void {
const {
LDAP_HOST = LDAP_HOST_CONST,
KEY_PATH,
CERT_PATH,
CA_CERT_PATH
} = process.env;
const options = {
url: LDAP_HOST,
tlsOptions: {
key: fs.readFileSync(KEY_PATH),
cert: fs.readFileSync(CERT_PATH),
ca: fs.readFileSync(CA_CERT_PATH)
}
};
ldapts = new Client(options);
await ldapts.bind('EXTERNAL');
// We want to make sure that the unbind happens regardless of an error
try {
// Do your search here i.e.
const result = await ldapts.search(...);
console.log('result', result);
} finally {
if (ldapts) {
ldapts.unbind();
}
}
}
// Assumes you've stored your keys in base64 to remove new lines and that they are in a single object.
async function bindFromString(): void {
const {
LDAP_HOST = LDAP_HOST_CONST,
KEY_NAME,
CERT_NAME,
CA_CERT_NAME,
SECERT_MANAGER_NAME
} = process.env;
const sm = new AWS.SecretManager({ apiVersion: '2017-10-17' });
const secrets = await sm.getSecertValue({
SecretId: SECERT_MANAGER_NAME,
VersionStage: "AWSCURRENT"
}).promise();
const options = {
url: LDAP_HOST,
tlsOptions: {
key: Buffer.from(secrets[KEY_NAME], 'base64').toString('ascii'),
cert: Buffer.from(secrets[CERT_NAME], 'base64').toString('ascii'),
ca: Buffer.from(secrets[CA_CERT_NAME], 'base64').toString('ascii')
}
};
ldapts = new Client(options);
await ldapts.bind('EXTERNAL');
// We want to make sure that the unbind happens regardless of an error
try {
// Do your search here
const result = await ldapts.search(...);
console.log('result', result);
} finally {
if (ldapts) {
ldapts.unbind();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment