First you must require crypto library:
const crypto = require('crypto');
Then, define some functions:
function someId() {
// function taken from https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid
// creates a random 20 characters hex string
return 'xxxxxxxxxxxxxxxxxxxx'.replace(/x/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function md5(str, encoding) {
return crypto.createHash('md5').update(str).digest(encoding);
}
function passwordDigest(created, nonce, pass) {
// Password_Digest = Base64 ( SHA-1 ( bytes(decode64(nonce)) + bytes(created) + bytes(password) ) )
let pd = Int8Array.from([...Int8Array.from(Buffer.from(nonce, 'base64')),
...Int8Array.from(Buffer.from(created)),
...Int8Array.from(Buffer.from(pass))]);
pd = crypto.createHash('sha1').update(pd).digest('base64');
return pd;
}
// for example
// console.log(passwordDigest('2006-07-26T15:16:00.925Z', 'lckJBnhGHAj4EGG3YuGXmg==', '1111'));
// must print 'LiP3J84wKHpA6sMOu2BVVZRGYSY='
Now you can calculate variables to embed them in the header:
const usernametoken = `UsernameToken-${Math.round(Math.random()*10000000).toString()}`;
const username = 'myUserName';
const passwd = 'myPassword'; // this will not be sent
const created = (new Date).toISOString();
const nonce = md5(someId().substr(0,16), 'base64'); // Only 16 characters length before md5!
const passworddigest = passwordDigest(created, nonce, passwd);
Then you replace the variables you have calculated in a soap header:
const header = `<soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken wsu:Id="${usernametoken}" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>${username}</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">${passworddigest}</wsse:Password>
<wsse:Nonce>${nonce}</wsse:Nonce>
<wsu:Created>${created}</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>`;
So, finally, you must embed this header in your <soapenv:Envelope> before the <soapenv:Body>.