Skip to content

Instantly share code, notes, and snippets.

@serhiiminin
Forked from JoeStanton/ntlm.js
Created October 4, 2021 13:06
Show Gist options
  • Save serhiiminin/2b08eccab33db059a48cf8979bb9c6f9 to your computer and use it in GitHub Desktop.
Save serhiiminin/2b08eccab33db059a48cf8979bb9c6f9 to your computer and use it in GitHub Desktop.
NTLM Authentication with node-fetch
/* eslint-disable no-console */
const https = require('https');
const fetch = require('node-fetch');
const ntlm = require('httpntlm').ntlm;
const keepAlive = new https.Agent({ keepAlive: true });
const handleErrors = (response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
};
const handshake = (url, authOpts) => fetch(url, {
headers: {
Connection: 'keep-alive',
Authorization: ntlm.createType1Message(authOpts),
},
agent: keepAlive,
})
.then(response => response.headers.get('www-authenticate'))
.then((auth) => {
if (!auth) {
throw new Error('Stage 1 NTLM handshake failed.');
}
const type2 = ntlm.parseType2Message(auth);
return ntlm.createType3Message(type2, authOpts);
});
const url = 'http://my-ntlm-auth-endpoint.com/abc';
const authOpts = {
username: 'AD_USERNAME',
password: 'AD_PASSWORD',
domain: 'AD_DOMAIN',
workstation: '',
};
handshake(url, authOpts).then(auth =>
fetch(url, {
headers: {
Authorization: auth,
'Content-Type': 'application/zip',
},
agent: keepAlive,
body: deploymentPkg,
}))
.then(handleErrors)
.then(() => console.log(`Done`))
.catch(e => console.error('Failed', e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment