Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
The 'soap' npm package is a SOAP client and server library for Node.js. It allows you to create SOAP clients to consume web services and also create SOAP servers to expose your own web services.
Create a SOAP Client
This feature allows you to create a SOAP client that can consume a SOAP web service. You provide the WSDL URL, and the client can then call the web service methods.
const soap = require('soap');
const url = 'http://example.com/wsdl?wsdl';
soap.createClient(url, function(err, client) {
if (err) throw err;
client.MyFunction({name: 'value'}, function(err, result) {
if (err) throw err;
console.log(result);
});
});
Create a SOAP Server
This feature allows you to create a SOAP server that exposes your own web service. You define the service and its methods, and provide the WSDL file.
const soap = require('soap');
const express = require('express');
const app = express();
const myService = {
MyService: {
MyPort: {
MyFunction: function(args) {
return { name: args.name };
}
}
}
};
const xml = require('fs').readFileSync('myservice.wsdl', 'utf8');
soap.listen(app, '/wsdl', myService, xml);
app.listen(8000);
Handle SOAP Headers
This feature allows you to add custom SOAP headers to your SOAP client requests. This can be useful for authentication or other custom header requirements.
const soap = require('soap');
const url = 'http://example.com/wsdl?wsdl';
soap.createClient(url, function(err, client) {
if (err) throw err;
const soapHeader = { 'MyHeader': 'value' };
client.addSoapHeader(soapHeader);
client.MyFunction({name: 'value'}, function(err, result) {
if (err) throw err;
console.log(result);
});
});
The 'strong-soap' package is another SOAP client and server library for Node.js. It is similar to 'soap' but offers additional features like better WSDL handling and support for more complex SOAP scenarios. It is maintained by the StrongLoop team.
The 'easy-soap-request' package is a lightweight SOAP client for Node.js. It focuses on simplicity and ease of use, making it a good choice for simple SOAP requests. However, it does not offer server-side capabilities like 'soap'.
The 'node-soap-client' package is a minimalistic SOAP client for Node.js. It is designed to be easy to use and integrates well with modern JavaScript features like Promises and async/await. It is a good alternative if you only need client-side functionality.
A SOAP client and server for node.js.
This module lets you connect to web services using SOAP. It also provides a server that allows you to run your own SOAP services.
Install with npm:
npm install soap
We've disabled issues in the repository and are now solely reviewing pull requests. The reasons why we disabled issues can be found here #731.
Community support can be found on gitter:
If you're looking for professional help you can contact the maintainers through this google form.
var soap = require('soap');
var url = 'http://example.com/wsdl?wsdl';
var args = {name: 'value'};
soap.createClient(url, function(err, client) {
client.MyFunction(args, function(err, result) {
console.log(result);
});
});
This client has a built in WSDL cache. You can use the disableCache
option to disable it.
var soap = require('soap');
var url = 'http://example.com/wsdl?wsdl';
var args = {name: 'value'};
soap.createClientAsync(url).then((client) => {
return client.MyFunctionAsync(args);
}).then((result) => {
console.log(result);
});
This client has a built in WSDL cache. You can use the disableCache
option to disable it.
The options
argument allows you to customize the client with the following properties:
.wsdl
file.<pre><soap:Body></soap:Body></pre>
.&
, >
, <
etc), default: true
.Invalid XML
SOAP fault on a bad request, default: false
.request(rurl, data, callback, exheaders, exoptions)
.Async
.[^a-z$_0-9]
), replace them with _
. Note: if using this option, clients using wsdls with two operations like soap:method
and soap-method
will be overwritten. Then, use bracket notation instead (client['soap:method']()
).{list: [{elem: 1}, {elem: 2}]}
are marshalled into xml as <list><elem>1</elem></list> <list><elem>2</elem></list>
. If false, marshalls into <list> <elem>1</elem> <elem>2</elem> </list>
. Default: true
.Note: for versions of node >0.10.X, you may need to specify {connection: 'keep-alive'}
in SOAP headers to avoid truncation of longer chunked responses.
server can be a http Server or express framework based server wsdl is an xml string that defines the service. callback a function to run after the server has been initialized.
var myService = {
MyService: {
MyPort: {
MyFunction: function(args) {
return {
name: args.name
};
},
// This is how to define an asynchronous function with a callback.
MyAsyncFunction: function(args, callback) {
// do some work
callback({
name: args.name
});
},
// This is how to define an asynchronous function with a Promise.
MyPromiseFunction: function(args) {
return new Promise((resolve) => {
// do some work
resolve({
name: args.name
});
});
},
// This is how to receive incoming headers
HeadersAwareFunction: function(args, cb, headers) {
return {
name: headers.Token
};
},
// You can also inspect the original `req`
reallyDetailedFunction: function(args, cb, headers, req) {
console.log('SOAP `reallyDetailedFunction` request from ' + req.connection.remoteAddress);
return {
name: headers.Token
};
}
}
}
};
var xml = require('fs').readFileSync('myservice.wsdl', 'utf8');
//http server example
var server = http.createServer(function(request,response) {
response.end('404: Not Found: ' + request.url);
});
server.listen(8000);
soap.listen(server, '/wsdl', myService, xml, function(){
console.log('server initialized');
});
//express server example
var app = express();
//body parser middleware are supported (optional)
app.use(bodyParser.raw({type: function(){return true;}, limit: '5mb'}));
app.listen(8001, function(){
//Note: /wsdl route will be handled by soap module
//and all other routes & middleware will continue to work
soap.listen(app, '/wsdl', myService, xml, function(){
console.log('server initialized');
});
});
You can pass in server and WSDL Options using an options hash.
Server options include the below:
pfx
: A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the key, cert and ca options.)key
: A string or Buffer containing the private key of the server in PEM format. (Could be an array of keys). (Required)passphrase
: A string of passphrase for the private key or pfx.cert
: A string or Buffer containing the certificate key of the server in PEM format. (Could be an array of certs). (Required)ca
: An array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.crl
: Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)ciphers
: A string describing the ciphers to use or exclude, separated by :. The default cipher suite is:enableChunkedEncoding
: A boolean for controlling chunked transfer encoding in response. Some client (such as Windows 10's MDM enrollment SOAP client) is sensitive to transfer-encoding mode and can't accept chunked response. This option let user disable chunked transfer encoding for such a client. Default to true
for backward compatibility.var xml = require('fs').readFileSync('myservice.wsdl', 'utf8');
soap.listen(server, {
// Server options.
path: '/wsdl',
services: myService,
xml: xml,
// WSDL options.
attributesKey: 'theAttrs',
valueKey: 'theVal',
xmlKey: 'theXml'
});
If the log
method is defined it will be called with 'received' and 'replied'
along with data.
server = soap.listen(...)
server.log = function(type, data) {
// type is 'received' or 'replied'
};
Server instances emit the following events:
function(request, methodName)
.function(response, methodName)
.function(headers, methodName)
.The sequence order of the calls is request
, headers
and then the dedicated
service method.
The so called one-way (or asynchronous) calls occur when an operation is called with no output defined in WSDL. The server sends a response (defaults to status code 200 with no body) to the client disregarding the result of the operation.
You can configure the response to match the appropriate client expectation to the SOAP standard implementation.
Pass in oneWay
object in server options. Use the following keys:
emptyBody
: if true, returns an empty body, otherwise no content at all (default is false)
responseCode
: default statusCode is 200, override it with this options (for example 202 for SAP standard compliant response)
A service method can reply with a SOAP Fault to a client by throw
ing an
object with a Fault
property.
throw {
Fault: {
Code: {
Value: 'soap:Sender',
Subcode: { value: 'rpc:BadArguments' }
},
Reason: { Text: 'Processing Error' }
}
};
To change the HTTP statusCode of the response include it on the fault. The statusCode property will not be put on the xml message.
throw {
Fault: {
Code: {
Value: 'soap:Sender',
Subcode: { value: 'rpc:BadArguments' }
},
Reason: { Text: 'Processing Error' },
statusCode: 500
}
};
If server.authenticate
is not defined then no authentication will take place.
Asynchronous authentication:
server = soap.listen(...)
server.authenticate = function(security, callback) {
var created, nonce, password, user, token;
token = security.UsernameToken, user = token.Username,
password = token.Password, nonce = token.Nonce, created = token.Created;
myDatabase.getUser(user, function (err, dbUser) {
if (err || !dbUser) {
callback(false);
return;
}
callback(password === soap.passwordDigest(nonce, created, dbUser.password));
});
};
Synchronous authentication:
server = soap.listen(...)
server.authenticate = function(security) {
var created, nonce, password, user, token;
token = security.UsernameToken, user = token.Username,
password = token.Password, nonce = token.Nonce, created = token.Created;
return user === 'user' && password === soap.passwordDigest(nonce, created, 'password');
};
The server.authorizeConnection
method is called prior to the soap service method.
If the method is defined and returns false
then the incoming connection is
terminated.
server = soap.listen(...)
server.authorizeConnection = function(req) {
return true; // or false
};
A service method can look at the SOAP headers by providing a 3rd arguments.
{
HeadersAwareFunction: function(args, cb, headers) {
return {
name: headers.Token
};
}
}
It is also possible to subscribe to the 'headers' event. The event is triggered before the service method is called, and only when the SOAP Headers are not empty.
server = soap.listen(...)
server.on('headers', function(headers, methodName) {
// It is possible to change the value of the headers
// before they are handed to the service method.
// It is also possible to throw a SOAP Fault
});
First parameter is the Headers object; second parameter is the name of the SOAP method that will called (in case you need to handle the headers differently based on the method).
Both client & server can define SOAP headers that will be added to what they send. They provide the following methods to manage the headers.
soapHeader
Object({rootName: {name: 'value'}}), strict xml-string,
or function (server only)For servers only, soapHeader
can be a function, which allows headers to be
dynamically generated from information in the request. This function will be
called with the following arguments for each received request:
methodName
The name of the request methodargs
The arguments of the requestheaders
The headers in the requestreq
The original request objectThe return value of the function must be an Object({rootName: {name: 'value'}}) or strict xml-string, which will be inserted as an outgoing header of the response to that request.
For example:
server = soap.listen(...);
server.addSoapHeader(function(methodName, args, headers, req) {
console.log('Adding headers for method', methodName);
return {
MyHeader1: args.SomeValueFromArgs,
MyHeader2: headers.SomeRequestHeader
};
// or you can return "<MyHeader1>SomeValue</MyHeader1>"
});
The index where the header is inserted.
name
Unknown parameter (it could just a empty string)namespace
prefix of xml namespacexmlns
URIindex
index of the header to replace with provided new valuesoapHeader
Object({rootName: {name: 'value'}}), strict xml-string
or function (server only)See addSoapHeader
for how to pass a function into soapHeader
.
An instance of Client
is passed to the soap.createClient
callback. It is used to execute methods on the soap service.
client.describe() // returns
{
MyService: {
MyPort: {
MyFunction: {
input: {
name: 'string'
}
}
}
}
}
client.MyFunction({name: 'value'}, function(err, result, rawResponse, soapHeader, rawRequest) {
// result is a javascript object
// rawResponse is the raw xml response string
// soapHeader is the response soap header as a javascript object
// rawRequest is the raw xml request string
})
The args
argument allows you to supply arguments that generate an XML document inside of the SOAP Body section.
The options
object is optional and is passed to the request
-module.
Interesting properties might be:
timeout
: Timeout in millisecondsforever
: Enables keep-alive connections and pools themattachments
: array of attachment objects. This converts the request into MTOM: headers['Content-Type']='multipart/related; type="application/xop+xml"; start= ... '
[{
mimetype: content mimetype,
contentId: part id,
name: file name,
body: binary data
},
...
]
forceMTOM
: set to True if you want to send the request as MTOM even if you don't have attachments client.MyFunctionAsync({name: 'value'}).then((result) => {
// result is a javascript array containing result, rawResponse, soapheader, and rawRequest
// result is a javascript object
// rawResponse is the raw xml response string
// soapHeader is the response soap header as a javascript object
// rawRequest is the raw xml request string
})
The args
argument allows you to supply arguments that generate an XML document inside of the SOAP Body section.
The options
object is optional and is passed to the request
-module.
Interesting properties might be:
timeout
: Timeout in millisecondsforever
: Enables keep-alive connections and pools themattachments
: array of attachment objects. This converts the request into MTOM: headers['Content-Type']='multipart/related; type="application/xop+xml"; start= ... '
[{
mimetype: content mimetype,
contentId: part id,
name: file name,
body: binary data
},
...
]
forceMTOM
: set to True if you want to send the request as MTOM even if you don't have attachmentsargs
The example above uses {name: 'value'}
as the args. This may generate a SOAP messages such as:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<Request xmlns="http://www.example.com/v1">
<name>value</name>
</Request>
</soapenv:Body>
</soapenv:Envelope>
Note that the "Request" element in the output above comes from the WSDL. If an element in args
contains no namespace prefix, the default namespace is assumed. Otherwise, you must add the namespace prefixes to the element names as necessary (e.g., ns1:name
).
Currently, when supplying JSON args, elements may not contain both child elements and a text value, even though that is allowed in the XML specification.
args
You may pass in a fully-formed XML string instead the individual elements in JSON args
and attributes that make up the XML. The XML string should not contain an XML declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>
) or a document type declaration (e.g., <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
).
var args = { _xml: "<ns1:MyRootElement xmlns:ns1="http://www.example.com/v1/ns1">
<ChildElement>elementvalue</ChildElement>
</ns1:MyRootElement>"
};
You must specify all of the namespaces and namespace prefixes yourself. The element(s) from the WSDL are not utilized as they were in the "Example with JSON as the args
" example above, which automatically populated the "Request" element.
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// result is a javascript object
})
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// result is a javascript object
}, {timeout: 5000})
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {time: true})
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {proxy: 'http://localhost:8888'})
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {postProcess: function(_xml) {
return _xml.replace('text', 'newtext');
}})
Object properties define extra HTTP headers to be sent on the request.
client.addHttpHeader('User-Agent', `CustomUserAgent`);
To align method call signature with node' standard callback-last patter and event allow promisification of method calls, the following method signatures are also supported:
client.MyService.MyPort.MyFunction({name: 'value'}, options, function (err, result) {
// result is a javascript object
})
client.MyService.MyPort.MyFunction({name: 'value'}, options, extraHeaders, function (err, result) {
// result is a javascript object
})
node-soap
is still working out some kinks regarding namespaces. If you find that an element is given the wrong namespace prefix in the request body, you can add the prefix to it's name in the containing object. I.E.:
client.MyService.MyPort.MyFunction({'ns1:name': 'value'}, function(err, result) {
// request body sent with `<ns1:name`, regardless of what the namespace should have been.
}, {timeout: 5000})
client.MyService.MyPort.MyFunction({':name': 'value'}, function(err, result) {
// request body sent with `<name`, regardless of what the namespace should have been.
}, {timeout: 5000})
Client instances emit the following events:
Emitted before a request is sent. The event handler has the signature (xml, eid)
.
Emitted before a request is sent, but only the body is passed to the event handler. Useful if you don't want to log /store Soap headers. The event handler has the signature (message, eid)
.
Emitted when an erroneous response is received. Useful if you want to globally log errors. The event handler has the signature (error, eid)
.
Emitted after a response is received. This is emitted for all responses (both success and errors). The event handler has the signature (body, response, eid)
IncomingMessage
response object.An 'exchange' is a request/response couple. Event handlers receive the exchange id in all events. The exchange id is the same for the requests events and the responses events, this way you can use it to retrieve the matching request when an response event is received.
By default exchange ids are generated by using node-uuid but you can use options in client calls to pass your own exchange id.
Example :
client.MyService.MyPort.MyFunction(args , function(err, result) {
}, {exchangeId: myExchangeId})
A WSDL instance can also be instantiated directly when you want to (un)marshal messages without doing SOAP calls. This can be used when a WSDL does not contain bindings for services (e.g. some Windows Communication Foundation SOAP web services).
Construct a WSDL instance from either the WSDL content or the URL to the WSDL.
{}
as default.Unmarshal XML to object.
Object containing the object types from the xml as keys.
Marshal an object to XML
XML representation of object.
// Abstracted from a real use case
import { AxiosInstance } from 'axios';
import { WSDL } from 'soap';
import { IProspectType } from './types';
// A WSDL in a string.
const WSDL_CONTENT = "...";
const httpClient: AxiosInstance = /* ... instantiate ... */;
const url = 'http://example.org/SoapService.svc';
const wsdl = new WSDL(WSDL_CONTENT, baseURL, {});
async function sampleGetCall(): IProspectType | undefined {
const res = await httpClient.get(`${baseURL}/GetProspect`);
const object = wsdl.xmlToObject(res.data);
if (!object.ProspectType) {
// Response did not contain the expected type
return undefined;
}
// Optionally, unwrap and set defaults for some fields
// Ensure that the object meets the expected prototype
// Finally cast and return the result.
return object.ProspectType as IProspectType;
}
async function samplePostCall(prospect: IProspectType) {
// objectToXML(object, typeName, namespacePrefix, namespaceURI, ...)
const objectBody = wsdl.objectToXML(obj, 'ProspectType', '', '');
const data = `<?xml version="1.0" ?>${body}`;
const res = await httpClient.post(`${baseURL}/ProcessProspect`, data);
// Optionally, deserialize request and return response status.
}
node-soap
has several default security protocols. You can easily add your own
as well. The interface is quite simple. Each protocol defines these optional methods:
addOptions(options)
- a method that accepts an options arg that is eventually passed directly to request
.addHeaders(headers)
- a method that accepts an argument with HTTP headers, to add new ones.toXML()
- a method that returns a string of XML to be appended to the SOAP headers. Not executed if postProcess
is also defined.postProcess(xml, envelopeKey)
- a method that receives the the assembled request XML plus envelope key, and returns a processed string of XML. Executed before options.postProcess
. client.setSecurity(new soap.BasicAuthSecurity('username', 'password'));
client.setSecurity(new soap.BearerSecurity('token'));
Note: If you run into issues using this protocol, consider passing these options as default request options to the constructor:
rejectUnauthorized: false
strictSSL: false
secureOptions: constants.SSL_OP_NO_TLSv1_2
(this is likely needed for node >= 10.0)If you want to reuse tls sessions, you can use the option forever: true
.
client.setSecurity(new soap.ClientSSLSecurity(
'/path/to/key',
'path/to/cert',
'/path/to/ca-cert', /*or an array of buffer: [fs.readFileSync('/path/to/ca-cert/1', 'utf8'),
'fs.readFileSync('/path/to/ca-cert/2', 'utf8')], */
{ /*default request options like */
// strictSSL: true,
// rejectUnauthorized: false,
// hostname: 'some-hostname'
// secureOptions: constants.SSL_OP_NO_TLSv1_2,
// forever: true,
},
));
Note: If you run into issues using this protocol, consider passing these options as default request options to the constructor:
rejectUnauthorized: false
strictSSL: false
secureOptions: constants.SSL_OP_NO_TLSv1_2
(this is likely needed for node >= 10.0)If you want to reuse tls sessions, you can use the option forever: true
.
client.setSecurity(new soap.ClientSSLSecurityPFX(
'/path/to/pfx/cert', // or a buffer: [fs.readFileSync('/path/to/pfx/cert', 'utf8'),
'path/to/optional/passphrase',
{ /*default request options like */
// strictSSL: true,
// rejectUnauthorized: false,
// hostname: 'some-hostname'
// secureOptions: constants.SSL_OP_NO_TLSv1_2,
// forever: true,
},
));
WSSecurity
implements WS-Security. UsernameToken and PasswordText/PasswordDigest is supported.
var options = {
hasNonce: true,
actor: 'actor'
};
var wsSecurity = new soap.WSSecurity('username', 'password', options)
client.setSecurity(wsSecurity);
the options
object is optional and can contain the following properties:
passwordType
: 'PasswordDigest' or 'PasswordText' (default: 'PasswordText'
)hasTimeStamp
: adds Timestamp element (default: true
)hasTokenCreated
: adds Created element (default: true
)hasNonce
: adds Nonce element (default: false
)mustUnderstand
: adds mustUnderstand=1 attribute to security tag (default: false
)actor
: if set, adds Actor attribute with given value to security tag (default: ''
)WS-Security X509 Certificate support.
var privateKey = fs.readFileSync(privateKeyPath);
var publicKey = fs.readFileSync(publicKeyPath);
var password = ''; // optional password
var options = {
hasTimeStamp: true,
additionalReferences: [
'wsa:Action',
'wsa:ReplyTo',
'wsa:To',
],
signerOptions: {
prefix: 'ds',
attrs: { Id: 'Signature' },
existingPrefixes: {
wsse: 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd',
}
}
var wsSecurity = new soap.WSSecurityCert(privateKey, publicKey, password, options);
client.setSecurity(wsSecurity);
The options
object is optional and can contain the following properties:
hasTimeStamp
: Includes Timestamp tags (default: true
)signatureTransformations
: sets the Reference Transforms Algorithm (default ['http://www.w3.org/2000/09/xmldsig#enveloped-signature', 'http://www.w3.org/2001/10/xml-exc-c14n#']). Type is a string arraysignatureAlgorithm
: set to http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
to use sha256additionalReferences
: (optional) Array of Soap headers that need to be signed. This need to be added using client.addSoapHeader('header')
signerOptions
: (optional) passes options to the XML Signer package - from (https://github.com/yaronn/xml-crypto)
existingPrefixes
: (optional) A hash of prefixes and namespaces prefix: namespace that shouldn't be in the signature because they already exist in the xml (default: { 'wsse': 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' }
)prefix
: (optional) Adds this value as a prefix for the generated signature tags.attrs
: (optional) A hash of attributes and values attrName: value to add to the signature root nodehasTimeStamp:true
<soap:Header>
<wsse:Security soap:mustUnderstand="1">
<wsse:BinarySecurityToken>XXX</wsse:BinarySecurityToken>
<!-- The Timestamp group of tags are added and signed -->
<Timestamp xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" Id="Timestamp">
<Created>2019-10-01T08:17:50Z</Created>
<Expires>2019-10-01T08:27:50Z</Expires>
</Timestamp>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
...
<Reference URI="#Timestamp">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>XyZ=</DigestValue>
</Reference>
</SignedInfo>
</Signature>
</wsse:Security>
</soap:Header>
additionalReferences: ['To']
<soap:Header>
<To Id="To">localhost.com</To>
<wsse:Security soap:mustUnderstand="1">
<wsse:BinarySecurityToken>XXX</wsse:BinarySecurityToken>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<!-- The "To" tag is signed and added as a reference -->
<Reference URI="#To">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>XYZ</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
Rf6M4F4puQuQHJIPtJz1CZIVvF3qOdpEEcuAiooWkX5ecnAHSf3RW3sOIzFUWW7VOOncJcts/3xr8DuN4+8Wm9hx1MoOcWJ6kyRIdVNbQWLseIcAhxYCntRY57T2TBXzpb0UPA56pry1+TEcnIQXhdIzG5YT+tTVTp+SZHHcnlP5Y+yqnIOH9wzgRvAovbydTYPCODF7Ana9K/7CSGDe7vpVT85CUYUcJE4DfTxaRa9gKkKrBdPN9vFVi0WfxtMF4kv23cZRCZzS5+CoLfPlx3mq65gVXsqH01RLbktNJq9VaQKcZUgapmUCMzrYhqyzUQJ8HrSHqe+ya2GsjlB0VQ==
</SignatureValue>
<KeyInfo>
<wsse:SecurityTokenReference
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:Reference URI="#x509-c5c0d213676f4a6ba5e6fa58074eb57a"
ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
</wsse:SecurityTokenReference>
</KeyInfo>
</Signature>
</wsse:Security>
</soap:Header>
signerOptions.prefix:'ds'
<soap:Header>
<To Id="To">localhost.com</To>
<wsse:Security soap:mustUnderstand="1">
<wsse:BinarySecurityToken>XXX</wsse:BinarySecurityToken>
<!-- Signature and children tags are given the prefix defined. -->
<ds:Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<ds:Reference URI="#To">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>XYZ</DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>
Rf6M4F4puQuQHJIPtJz1CZIVvF3qOdpEEcuAiooWkX5ecnAHSf3RW3sOIzFUWW7VOOncJcts/3xr8DuN4+8Wm9hx1MoOcWJ6kyRIdVNbQWLseIcAhxYCntRY57T2TBXzpb0UPA56pry1+TEcnIQXhdIzG5YT+tTVTp+SZHHcnlP5Y+yqnIOH9wzgRvAovbydTYPCODF7Ana9K/7CSGDe7vpVT85CUYUcJE4DfTxaRa9gKkKrBdPN9vFVi0WfxtMF4kv23cZRCZzS5+CoLfPlx3mq65gVXsqH01RLbktNJq9VaQKcZUgapmUCMzrYhqyzUQJ8HrSHqe+ya2GsjlB0VQ==
</ds:SignatureValue>
<ds:KeyInfo>
<wsse:SecurityTokenReference
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:Reference URI="#x509-c5c0d213676f4a6ba5e6fa58074eb57a"
ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
</wsse:Security>
</soap:Header>
signerOptions.attrs:{ Id: 'signature-100', foo:'bar'}
<soap:Header>
<wsse:Security soap:mustUnderstand="1">
<wsse:BinarySecurityToken>XXX</wsse:BinarySecurityToken>
<!-- The Timestamp group of tags are added and signed -->
<Timestamp xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" Id="Timestamp">
<Created>2019-10-01T08:17:50Z</Created>
<Expires>2019-10-01T08:27:50Z</Expires>
</Timestamp>
<Signature Id="signature-100" foo="bar" xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
...
<Reference URI="#Timestamp">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>XyZ=</DigestValue>
</Reference>
</SignedInfo>
</Signature>
</wsse:Security>
</soap:Header>
Parameter invocation:
client.setSecurity(new soap.NTLMSecurity('username', 'password', 'domain', 'workstation'));
This can also be set up with a JSON object, substituting values as appropriate, for example:
var loginData = {username: 'username', password: 'password', domain: 'domain', workstation: 'workstation'};
client.setSecurity(new soap.NTLMSecurity(loginData));
Sometimes it is necessary to override the default behaviour of node-soap
in order to deal with the special requirements
of your code base or a third library you use. Therefore you can use the wsdlOptions
Object, which is passed in the
#createClient()
method and could have any (or all) of the following contents:
var wsdlOptions = {
attributesKey: 'theAttrs',
valueKey: 'theVal',
xmlKey: 'theXml'
}
If nothing (or an empty Object {}
) is passed to the #createClient()
method, the node-soap
defaults (attributesKey: 'attributes'
, valueKey: '$value'
and xmlKey: '$xml'
) are used.
value
keyBy default, node-soap
uses $value
as the key for any parsed XML value which may interfere with your other code as it
could be some reserved word, or the $
in general cannot be used for a key to start with.
You can define your own valueKey
by passing it in the wsdl_options
to the createClient call:
var wsdlOptions = {
valueKey: 'theVal'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
// your code
});
xml
keyBy default, node-soap
uses $xml
as the key to pass through an XML string as is; without parsing or namespacing it. It overrides all the other content that the node might have otherwise had.
For example :
{
dom: {
nodeone: {
$xml: '<parentnode type="type"><childnode></childnode></parentnode>',
siblingnode: 'Cant see me.'
},
nodetwo: {
parentnode: {
attributes: {
type: 'type'
},
childnode: ''
}
}
}
};
could become
<tns:dom>
<tns:nodeone>
<parentnode type="type">
<childnode></childnode>
</parentnode>
</tns:nodeone>
<tns:nodetwo>
<tns:parentnode type="type">
<tns:childnode></tns:childnode>
</tns:parent>
</tns:nodetwo>
</tns:dom>
You can define your own xmlKey
by passing it in the wsdl_options
object to the createClient call:
var wsdlOptions = {
xmlKey: 'theXml'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
// your code
});
attributes
keyBy default, node-soap
uses attributes
as the key to define a nodes attributes.
{
parentnode: {
childnode: {
attributes: {
name: 'childsname'
},
$value: 'Value'
}
}
}
could become
<parentnode>
<childnode name="childsname">Value</childnode>
</parentnode>
However, attributes
may be a reserved key for some systems that actually want a node called attributes
<attributes>
</attributes>
You can define your own attributesKey
by passing it in the wsdl_options
object to the createClient call:
var wsdlOptions = {
attributesKey: '$attributes'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
client.method({
parentnode: {
childnode: {
$attributes: {
name: 'childsname'
},
$value: 'Value'
}
}
});
});
By default, WSDL and schema files import other schemas and types using relative paths.
However in some systems (i.e. NetSuite) when the wsdl is downloaded for offline caching, all files are flattened under a single directory and all the imports fail.
Passing this option allows node-soap
to correctly load all files.
var options ={
wsdl_options = { fixedPath: true }
};
soap.createClient(__dirname+'/wsdl/fixedPath/netsuite.wsdl', options, function(err, client) {
// your code
});
In rare cases, you may want to precisely control the namespace definition that is included in the root element.
You can specify the namespace definitions by setting the overrideRootElement
key in the wsdlOptions
like so:
var wsdlOptions = {
overrideRootElement: {
namespace: 'xmlns:tns',
xmlnsAttributes: [{
name: 'xmlns:ns2',
value: "http://tempuri.org/"
}, {
name: 'xmlns:ns3',
value: "http://sillypets.com/xsd"
}]
}
};
To see it in practice, have a look at the sample files in: test/request-response-samples/addPets__force_namespaces
Sometimes it's useful to handle deserialization in your code instead of letting node-soap do it. For example if the soap response contains dates that are not in a format recognized by javascript, you might want to use your own function to handle them.
To do so, you can pass a customDeserializer
object in options
. The properties of this object are the types that your deserializer handles itself.
Example :
var wsdlOptions = {
customDeserializer: {
// this function will be used to any date found in soap responses
date: function (text, context) {
/* text is the value of the xml element.
context contains the name of the xml element and other infos :
{
name: 'lastUpdatedDate',
object: {},
schema: 'xsd:date',
id: undefined,
nil: false
}
*/
return text;
}
}
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
...
});
The XML specification specifies that there is no semantic difference between <Tag></Tag>
and <Tag />
, and node-soap defaults to using the <Tag></Tag>
format. But if your web service is particular, or if there is a stylistic preference, the useEmptyTag
option causes tags with no contents to use the <Tag />
format instead.
var wsdlOptions = {
useEmptyTag: true
};
For example: { MyTag: { attributes: { MyAttr: 'value' } } }
is:
<MyTag MyAttr="value"></MyTag>
<MyTag MyAttr="value" />
If an Element in a schema
definition depends on an Element which is present in the same namespace, normally the tns:
namespace prefix is used to identify this Element. This is not much of a problem as long as you have just one schema
defined
(inline or in a separate file). If there are more schema
files, the tns:
in the generated soap
file resolved mostly to the parent wsdl
file,
which was obviously wrong.
node-soap
now handles namespace prefixes which shouldn't be resolved (because it's not necessary) as so called ignoredNamespaces
which default to an Array of 3 Strings (['tns', 'targetNamespace', 'typedNamespace']
).
If this is not sufficient for your purpose you can easily add more namespace prefixes to this Array, or override it in its entirety
by passing an ignoredNamespaces
object within the options
you pass in soap.createClient()
method.
A simple ignoredNamespaces
object, which only adds certain namespaces could look like this:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace']
}
}
This would extend the ignoredNamespaces
of the WSDL
processor to ['tns', 'targetNamespace', 'typedNamespace', 'namespaceToIgnore', 'someOtherNamespace']
.
If you want to override the default ignored namespaces you would simply pass the following ignoredNamespaces
object within the options
:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace'],
override: true
}
}
This would override the default ignoredNamespaces
of the WSDL
processor to ['namespaceToIgnore', 'someOtherNamespace']
. (This shouldn't be necessary, anyways).
If you want to override the default ignored namespaces you would simply pass the following ignoredNamespaces
object within the options
:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace'],
override: true
}
}
This would override the default ignoredNamespaces
of the WSDL
processor to ['namespaceToIgnore', 'someOtherNamespace']
. (This shouldn't be necessary, anyways).
If an Element in a schema
definition depends has a basenamespace defined but the request does not need that value, for example you have a "sentJob" with basenamespace "v20"
but the request need only: set in the tree structure, you need to set the ignoreBaseNameSpaces to true. This is set because in a lot of workaround the wsdl structure is not correctly
set or the webservice bring errors.
By default the attribute is set to true. An example to use:
A simple ignoredNamespaces
object, which only adds certain namespaces could look like this:
var options = {
ignoredNamespaces: true
}
Unit testing services that use soap clients can be very cumbersome. In order to get
around this you can use soap-stub
in conjunction with sinon
to stub soap with
your clients.
// test-initialization-script.js
var sinon = require('sinon');
var soapStub = require('soap/soap-stub');
var urlMyApplicationWillUseWithCreateClient = 'http://path-to-my-wsdl';
var clientStub = {
SomeOperation: sinon.stub()
};
clientStub.SomeOperation.respondWithError = soapStub.createErroringStub({..error json...});
clientStub.SomeOperation.respondWithSuccess = soapStub.createRespondingStub({..success json...});
soapStub.registerClient('my client alias', urlMyApplicationWillUseWithCreateClient, clientStub);
// test.js
var soapStub = require('soap/soap-stub');
describe('myService', function() {
var clientStub;
var myService;
beforeEach(function() {
clientStub = soapStub.getStub('my client alias');
soapStub.reset();
myService.init(clientStub);
});
describe('failures', function() {
beforeEach(function() {
clientStub.SomeOperation.respondWithError();
});
it('should handle error responses', function() {
myService.somethingThatCallsSomeOperation(function(err, response) {
// handle the error response.
});
});
});
});
FAQs
A minimal node SOAP client
The npm package soap receives a total of 0 weekly downloads. As such, soap popularity was classified as not popular.
We found that soap demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.