Setting Authorization in Node.js SOAP Client - node.js

I want to access a WSDL service through SOAP Client in Node.js. I used soap node module. But I can't able to find any documentation to set username and password. I'm not going to create SOAP server, I just want SOAPClient which is similar to PHP's SoapClient, using which I should able to access the WSDL service.
Update:
I had forked and customised the source to support this feature https://github.com/sincerekamal/node-soap

You can provide username and password like this:
var soap = require('soap');
var url = 'your WSDL url';
var auth = "Basic " + new Buffer("your username" + ":" + "your password").toString("base64");
soap.createClient(url, { wsdl_headers: {Authorization: auth} }, function(err, client) {
});
(derived from https://github.com/vpulim/node-soap/issues/56, thank you Gabriel Lucena https://github.com/glucena)

Another option to add basic authentication is using client.addHttpHeader. I tried both setSecurity and setting wsdl_headers but neither worked for me when authenticating to Cisco CUCM AXL.
Here is what worked for me:
var soap = require('soap');
var url = 'AXLAPI.wsdl'; // Download this file and xsd files from cucm admin page
var auth = "Basic " + new Buffer("your username" + ":" + "your password").toString("base64");
soap.createClient(url,function(err,client){
client.addHttpHeader('Authorization',auth);
});

Just to share what I've read from https://github.com/vpulim/node-soap:
var soap = require('soap');
var url = 'your WSDL url';
soap.createClient(url, function(err, client) {
client.setSecurity(new soap.BasicAuthSecurity('your username','your password'));
});

You need to set the username and password by passing the authorisation to the wsdl_headers object e.g
var auth = "Basic " + new Buffer('username' + ':' + 'password').toString("base64");
var client = Soap.createClient('wsdlUrl', { wsdl_headers: { Authorization: auth } }, (err, client) => {
if (err) {
throw err;
} else {
client.yourMethod();
}
});

A small tweak to the existing answers: you can use your security object to create the header for the WSDL request too, e.g.
const security = new soap.BasicAuthSecurity(username, password);
const wsdl_headers = {};
security.addHeaders(wsdl_headers);
soap.createClientAsync(url, { wsdl_headers }).then((err, client) => {
client.setSecurity(security);
// etc.
});
Or if you're using something more complicated than BasicAuthSecurity you may also need to set wsdl_options from the security object, e.g.
const security = new soap.NTLMSecurity(username, password, domain, workstation);
const wsdl_headers = {}, wsdl_options = {};
security.addHeaders(wsdl_headers);
security.addOptions(wsdl_options);
soap.createClientAsync(url, { wsdl_headers, wsdl_options }).then((err, client) => {
client.setSecurity(security);
// etc.
});

Related

Dynamics Business Central Azure AD ADAL Unauthorized

I developed a bare bones express app to test auth with Dynamics Business Central and ADAL in NodeJS. I'm getting the following 401 error. The authentication works as expected in Postman and I'm able to call the Dynamics REST endpoint in that context. In the JavaScript below I am using the same AAD tenant, client id, and client secret in Postman, but I'm not able to authenticate.
Compared the auth tokens given over Postman and in NodeJs using https://jwt.io/ and the only difference is the header values and the uti in the payload.
When I hit me getcompanies route I get the following error. I've listed my node package versions at the bottom of the post.
Error { error: { code: '401', message: 'Unauthorized' } }
Source code
var AuthenticationContext = require('adal-node').AuthenticationContext;
var crypto = require('crypto');
var express = require('express');
var request = require('request');
require('dotenv').config()
var clientId = process.env.CLIENT_ID;
var clientSecret = process.env.CLIENT_SECRET;
var authorityHostUrl = 'https://login.windows.net';
var azureAdTenant = 'grdegr.onmicrosoft.com';
var dynBusinessCentralCommonEndpoint = 'https://api.businesscentral.dynamics.com/v1.0/' + azureAdTenant + '/api/beta';
var bcRedirectUri = 'http://localhost:1337/getbctoken';
var dynBusinessCentralAuthUrl = authorityHostUrl + '/' +
azureAdTenant +
'/oauth2/authorize?response_type=code&client_id=' +
clientId +
'&redirect_uri=' +
bcRedirectUri +
'&state=<state>&resource=' +
'https://api.businesscentral.dynamics.com';
var app = express();
var port = 1337;
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.get('/bcauth', function(req, res) {
crypto.randomBytes(48, function(ex, buf) {
var bcToken = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
res.cookie('bcauthstate', bcToken);
var dynBusinessCentralAuthUrlauthorizationUrl = dynBusinessCentralAuthUrl.replace('<state>', bcToken);
console.log('redirecting to auth url: ' + dynBusinessCentralAuthUrlauthorizationUrl);
res.redirect(dynBusinessCentralAuthUrlauthorizationUrl);
});
});
var bcAccessToken = '';
app.get('/getbctoken', function(req, res) {
var authorityUrl = authorityHostUrl + '/' + azureAdTenant;
var authenticationContext = new AuthenticationContext(authorityUrl);
console.log('getting bc auth context');
authenticationContext.acquireTokenWithAuthorizationCode(
req.query.code,
bcRedirectUri,
'https://api.businesscentral.dynamics.com/',
clientId,
clientSecret,
function(err, response) {
var message = '';
if (err) {
message = 'error: ' + err.message + '\n';
return res.send(message)
}
bcAccessToken = response.accessToken;
console.log('bc token\n' + bcAccessToken);
res.send('bc access token updated');
}
);
});
app.get('/getcompanies', (req, res) => {
var body = '';
var options = {
url: 'https://api.businesscentral.dynamics.com/v1.0/grdegr.onmicrosoft.com/api/beta/companies',
method: 'GET',
headers: {
Authorization: 'Bearer ' + bcAccessToken
},
json: JSON.stringify(body)
};
request(options, (err, response, body) => {
res.send(response || err);
if (response) {
console.log(body);
}
else {
console.log('response is null');
}
});
});
Node Packages
"devDependencies": {
"adal-node": "^0.1.28",
"request": "^2.87.0",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8"
},
"dependencies": {
"dotenv": "^6.1.0"
}
Some services are very strict when checking the aud (audience) value of an access token. Dynamics 365 Business Central expects the access token audience to be exactly https://api.businesscentral.dynamics.com. In your code, you are asking for, and getting an access token for https://api.businesscentral.dynamics.com/. That trailing slash at the end is what is making Dynamics 365 reject your access token invalid.
Change the token request to:
authenticationContext.acquireTokenWithAuthorizationCode(
req.query.code,
bcRedirectUri,
'https://api.businesscentral.dynamics.com', // <-- No trailing slash!
clientId,
clientSecret,
// ...
...and it should work.
However, there are two important things to note in your sample:
The pattern you are following is a bit strange, though it may be because you're in the early stages of development, or because it was just a minimal repro example for this question. You should not store an access token that way, because the next person who calls /getcompanies will be able to do so calling on behalf of the user who originally signed in, instead of signing in themselves. If you are looking to have users sign in with Azure AD and as part of that, call Dynamics 365 on behalf of the signed-in user, I suggest looking at passport-azure-ad.
Especially if you plan to have a system-wide account or access token, be very careful returning the original response to the end user. This is true even when developing, since it's very easy to overlook something like that when moving to production, and exposing what could be a very privileged access token to an unauthorized user.

Sign in to Nodejs web app, using Azure AD

I'm trying to figure out how you can authenticate users using Azure AD. In order to experiment, I tried the example from Microsoft, found at https://github.com/Azure-Samples/active-directory-node-webapp-openidconnect.
I've set up an Active Directory in Azure, and added a new application called test with add id uri: http://testmagnhalv.
Now, when I run the server, following the instructions in the readme, I get redirected to login.microsoftonline.com and promted to log in. But when I provide username/pw, I get redirected back to the login page again.
I suspect the problem is that I don't set the variables in the config.json correctly, but I'm having a hard time finding documentation for what values need to be set.
Anyone got any experience with this example?
At first you must to add your app to active directory then use ADAL (Active Directory Authentication Library) for nodeJS
npm install adal-node
prepare your app for authentication referencing azure AD App registration values.
var AuthenticationContext = require('adal-node').AuthenticationContext;
var clientId = 'yourClientIdHere';
var clientSecret = 'yourAADIssuedClientSecretHere'
var redirectUri = 'yourRedirectUriHere';
var authorityHostUrl = 'https://login.windows.net';
var tenant = 'myTenant';
var authorityUrl = authorityHostUrl + '/' + tenant;
var redirectUri = 'http://localhost:3000/getAToken';
var resource = '00000002-0000-0000-c000-000000000000';
var templateAuthzUrl = 'https://login.windows.net/' +
tenant +
'/oauth2/authorize?response_type=code&client_id=' +
clientId +
'&redirect_uri=' +
redirectUri + '
&state=<state>&resource=' +
resource;
Now you need to get authorized with the token.
function createAuthorizationUrl(state) {
return templateAuthzUrl.replace('<state>', state);
}
// Clients get redirected here in order to create an OAuth authorize url and redirect them to AAD.
// There they will authenticate and give their consent to allow this app access to
// some resource they own.
app.get('/auth', function(req, res) {
crypto.randomBytes(48, function(ex, buf) {
var token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
res.cookie('authstate', token);
var authorizationUrl = createAuthorizationUrl(token);
res.redirect(authorizationUrl);
});
});
And finally handle the auth redirection
// After consent is granted AAD redirects here. The ADAL library is invoked via the
// AuthenticationContext and retrieves an access token that can be used to access the
// user owned resource.
app.get('/getAToken', function(req, res) {
if (req.cookies.authstate !== req.query.state) {
res.send('error: state does not match');
}
var authenticationContext = new AuthenticationContext(authorityUrl);
authenticationContext.acquireTokenWithAuthorizationCode(
req.query.code,
redirectUri,
resource,
clientId,
clientSecret,
function(err, response) {
var errorMessage = '';
if (err) {
errorMessage = 'error: ' + err.message + '\n';
}
errorMessage += 'response: ' + JSON.stringify(response);
res.send(errorMessage);
}
);
});
You can find the full example, and more here in ADAL for nodeJS repository:
Windows Azure Active Directory Authentication Library (ADAL) for Node.js
This is a simple but full demo taken from GitHub ADAL repository
website-sample.js
'use strict';
var express = require('express');
var logger = require('connect-logger');
var cookieParser = require('cookie-parser');
var session = require('cookie-session');
var fs = require('fs');
var crypto = require('crypto');
var AuthenticationContext = require('adal-node').AuthenticationContext;
var app = express();
app.use(logger());
app.use(cookieParser('a deep secret'));
app.use(session({secret: '1234567890QWERTY'}));
app.get('/', function(req, res) {
res.redirect('login');
});
/*
* You can override the default account information by providing a JSON file
* with the same parameters as the sampleParameters variable below. Either
* through a command line argument, 'node sample.js parameters.json', or
* specifying in an environment variable.
* {
* "tenant" : "rrandallaad1.onmicrosoft.com",
* "authorityHostUrl" : "https://login.windows.net",
* "clientId" : "624ac9bd-4c1c-4686-aec8-e56a8991cfb3",
* "clientSecret" : "verySecret="
* }
*/
var parametersFile = process.argv[2] || process.env['ADAL_SAMPLE_PARAMETERS_FILE'];
var sampleParameters;
if (parametersFile) {
var jsonFile = fs.readFileSync(parametersFile);
if (jsonFile) {
sampleParameters = JSON.parse(jsonFile);
} else {
console.log('File not found, falling back to defaults: ' + parametersFile);
}
}
if (!parametersFile) {
sampleParameters = {
tenant : 'rrandallaad1.onmicrosoft.com',
authorityHostUrl : 'https://login.windows.net',
clientId : '624ac9bd-4c1c-4686-aec8-b56a8991cfb3',
username : 'frizzo#naturalcauses.com',
password : ''
};
}
var authorityUrl = sampleParameters.authorityHostUrl + '/' + sampleParameters.tenant;
var redirectUri = 'http://localhost:3000/getAToken';
var resource = '00000002-0000-0000-c000-000000000000';
var templateAuthzUrl = 'https://login.windows.net/' + sampleParameters.tenant + '/oauth2/authorize?response_type=code&client_id=<client_id>&redirect_uri=<redirect_uri>&state=<state>&resource=<resource>';
app.get('/', function(req, res) {
res.redirect('/login');
});
app.get('/login', function(req, res) {
console.log(req.cookies);
res.cookie('acookie', 'this is a cookie');
res.send('\
<head>\
<title>FooBar</title>\
</head>\
<body>\
Login\
</body>\
');
});
function createAuthorizationUrl(state) {
var authorizationUrl = templateAuthzUrl.replace('<client_id>', sampleParameters.clientId);
authorizationUrl = authorizationUrl.replace('<redirect_uri>',redirectUri);
authorizationUrl = authorizationUrl.replace('<state>', state);
authorizationUrl = authorizationUrl.replace('<resource>', resource);
return authorizationUrl;
}
// Clients get redirected here in order to create an OAuth authorize url and redirect them to AAD.
// There they will authenticate and give their consent to allow this app access to
// some resource they own.
app.get('/auth', function(req, res) {
crypto.randomBytes(48, function(ex, buf) {
var token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
res.cookie('authstate', token);
var authorizationUrl = createAuthorizationUrl(token);
res.redirect(authorizationUrl);
});
});
// After consent is granted AAD redirects here. The ADAL library is invoked via the
// AuthenticationContext and retrieves an access token that can be used to access the
// user owned resource.
app.get('/getAToken', function(req, res) {
if (req.cookies.authstate !== req.query.state) {
res.send('error: state does not match');
}
var authenticationContext = new AuthenticationContext(authorityUrl);
authenticationContext.acquireTokenWithAuthorizationCode(req.query.code, redirectUri, resource, sampleParameters.clientId, sampleParameters.clientSecret, function(err, response) {
var message = '';
if (err) {
message = 'error: ' + err.message + '\n';
}
message += 'response: ' + JSON.stringify(response);
if (err) {
res.send(message);
return;
}
// Later, if the access token is expired it can be refreshed.
authenticationContext.acquireTokenWithRefreshToken(response.refreshToken, sampleParameters.clientId, sampleParameters.clientSecret, resource, function(refreshErr, refreshResponse) {
if (refreshErr) {
message += 'refreshError: ' + refreshErr.message + '\n';
}
message += 'refreshResponse: ' + JSON.stringify(refreshResponse);
res.send(message);
});
});
});
app.listen(3000);
console.log('listening on 3000');
https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/blob/master/sample/website-sample.js
As I known, I suggest you can follow the two documents below as references to get start.
Web App Sign In & Sign Out with Azure AD https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-openidconnect-nodejs/
Integrating Azure AD into a NodeJS web application https://azure.microsoft.com/en-us/documentation/samples/active-directory-node-webapp-openidconnect/
For developing easier, you can try to use the node package passport-azure-ad(https://github.com/AzureAD/passport-azure-ad) that is the one strategy of passport (http://passportjs.org/) for NodeJS to implement your needs.
I had similar problem and able to resolve it. After googling i made two changes in config.js.
issuer value set to false.
responseMode value changed from query to form_post.
config.js :
exports.creds = {
issuer : false,
realm : "<TENANT>",
returnURL: 'http://localhost:3000/auth/openid/return',
identityMetadata: 'https://login.microsoftonline.com/common/.well-known/openid-configuration', // For using Microsoft you should never need to change this.
clientID: '<CLIENT_ID>',
clientSecret: '<CLIENT_SECRET>', // if you are doing code or id_token code
skipUserProfile: true, // for AzureAD should be set to true.
responseType: 'id_token code', // for login only flows use id_token. For accessing resources use `id_token code`
responseMode: 'form_post', // For login only flows we should have token passed back to us in a POST
};

Login With Evernote

I'm trying to connect Evernote with Meteor.
But I'm having a really bad time, trying to get the Oauth token, I was trying to follow this example Evernote Sample Meteor, but is pretty old (2 years), but I tried to follow it and I got the idea.
I can get the connect to evernote, the login page and the email verification, my problem raised on the Meteor Method.
handleCallback, which need the "verify" param, which in this case is the
ouath_token
Second try.
On the evernote npm README they suggest to use oAuthjs, and I try with this code.
var hostName = "http://sandbox.evernote.com";
var options,oauth;
options = {
consumerKey: 'xxxxxxxxx',
consumerSecret: 'xxxxxxxxx',
callbackUrl : 'http://localhost:3000/oauth/auth',
signatureMethod : "HMAC-SHA1",
};
oauth.request({'method': 'GET', 'url': hostName + '/oauth',
'success': function(data){
console.log(data);
}, 'failure': function(data){
console.log(data);
}});
But it returns
(STDERR) No valid request transport found.
So I'm pretty stuck here.
The npm module provided by Evernote includes helper functions to get OAuth working.
Install the Evernote npm module via:
$npm install evernote
Below is the simplest single file example of implementing OAuth in a Evernote application I could put together. Just change the values of CONSUMER_KEY and CONSUMER_SECRET below and it should run just fine if you've installed Evernote:
var Evernote = require('evernote').Evernote;
var http = require("http");
var url = require("url");
CONSUMER_KEY="Put your consumer key here";
CONSUMER_SECRET="put your consumer secret here";
if (CONSUMER_KEY === "Put your consumer key here"){
console.error("\nPlease enter your Evernote consumer key and secret\n\nIf you don't have a key you can get one at:\nhttps://dev.evernote.com/#apikey\n")
process.exit(1)
}
var global = {};
global.oauthToken = '';
global.oauthSecret = '';
function getOauthVerifier(url) {
var regex = new RegExp("[\\?&]oauth_verifier=([^&#]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var handler = function(request, response) {
var params = url.parse(request.url)
var pathname = params.pathname;
console.log("Request for " + pathname + " received.");
var client = new Evernote.Client ({
consumerKey: "Put your consumer key here",
consumerSecret: "put your consumer secret here",
sandbox: true
});
if (pathname == "/"){
var callbackUrl = 'http://localhost:8888/oauth';
client.getRequestToken(callbackUrl, function(err, oauthToken, oauthSecret, results){
if(err) {
console.log(err);
}
else {
global.oauthToken = oauthToken;
global.oauthSecret = oauthSecret;
console.log("set oauth token and secret");
var authorizeUrl = client.getAuthorizeUrl(oauthToken);
console.log(authorizeUrl);
response.writeHead(200, {"Content-Type":"text/html"});
response.write("Please click here to authorize the application");
response.end();
}
});
}
else if (pathname == "/oauth"){
client.getAccessToken(
global.oauthToken,
global.oauthSecret,
getOauthVerifier(params.search),
function(error, oauthAccessToken, oauthAccessTokenSecret, results) {
if(error) {
console.log("error\n\n\n");
console.log(error);
}
else {
response.writeHead(200, {"Content-Type":"text/html"});
response.write(oauthAccessToken);
response.end();
}
}
);
}
else {
response.writeHead(200, {"Content-Type":"text/html"});
response.write("not a valid URL GO HOME ");
response.end();
}
};
http.createServer(handler).listen(8888);

Node soap, consume password protected WSDL

I'm trying to build a SOAP client with Node, I'm using "soap" package (https://www.npmjs.org/package/soap) trying to consume a user/password protected WSDL.
I can't find how to pass those credentials before creating the client by "soap.createClient", and of course, I can't retrieve the WSDL if I don't provide the right credentials.
I've tried doing:
soap.security.WSSecurity('user', 'pass');
and then calling "createClient" but to no avail.
Also, I've tried to do it with the node-soap-client, with this client I (apparently) can connect to the WSDL, but after that, I've no idea where to go (how to invoke methods).
What am I doing wrong?
Thanks for all your help!
Username and password credentials can be passed like this:
var soap = require('soap');
var url = 'your WSDL url';
var auth = "Basic " + new Buffer("your username" + ":" + "your password").toString("base64");
soap.createClient(url, { wsdl_headers: {Authorization: auth} }, function(err, client) {
});
(derived from https://github.com/vpulim/node-soap/issues/56, thank you Gabriel Lucena https://github.com/glucena)
If its password protected you also need to check the correct security mechanism. I spend a day trying to figure out that the service used NTLM security(it was a clients project and I only got username and password to access the wsdl). In that case, you would need to pass the correct wsdl_options object
var wsdl_options = {
ntlm: true,
username: "your username",
password: "your password",
domain: "domain",
workstation: "workstation"
}
soap.createClient(data.credentials[data.type], {
wsdl_options
},
function(err, client) {
console.log(client.describe());
});
Also, you would need to setSecurity on the client before using any service.
the link to complete explanation: https://codecalls.com/2020/05/17/using-soap-with-node-js/
when I added the auth to the headers I still had a problem. After reading the code and a number of articles I found this to work.
// or use local wsdl if security required
let url = 'http://service.asmx?wsdl'
let wsdl = 'wsdl.wsdl';
let soap = require('soap');
let util = require('util')
soap.createClient(wsdl, function(err, client) {
//don't forget to double slash the string or else the base64 will be incorrect
client.setSecurity(new soap.BasicAuthSecurity('admin\\userName', 'password'));
client.MethodFromWSDL(args, function (err, result) {
console.log(util.inspect(result,{depth: null}))
});
});
This worked for me, the API required the auth parameters as
<UserDetails xmlns="http://url/">';
<userName>{$Username}</userName>
<password>{$Password}</password>
<program>{$program}</program>
</UserDetails>
After lots of trial and error - this ended working
const soapHeader = {
UserDetails: {
userName: process.env.userName,
password: process.env.password,
program: process.env.program
}
}
...
soap.createClient(path, function (err, client) {
if (err) {
console.log('Error creating SOAP client: ' + err);
}
client.addSoapHeader(soapHeader, "", "tns", process.env.URN);
client[process.env.FUNCTION](sargs, function (err, result, rawResponse, soapHeader, rawRequest) {
if (err) {
console.log('Error call SOAP function ' + process.env.FUNCTION + ': ', err);
}
else {
console.log(result);
}
...

how to set headers using node-soap in node.js

I am trying to consume a wsdl service and found node-soap, but I cannot find how to set some headers.
Example :
header = {
"Username": "foo",
"Password" : "bar"
}
The reason I need this is because the wsdl I am trying to consume requires the username and password via the headers.
Thanks in advance
It may not be useful now however inorder to answering this question which is still open, here it goes.
You can make use of the method Client.addSoapHeader. As per the documentation
Client.addSoapHeader(soapHeader[, name, namespace, xmlns]) - add
soapHeader to soap:Header node
Options
soapHeader Object({rootName: {name: "value"}}) or strict xml-string
Optional parameters when first arg is object :
name Unknown parameter (it could just a empty string)
namespace prefix of xml namespace
xmlns URI
So you need to create an object and pass that to this method like:
var soapHeader = {
"Username": "foo",
"Password" : "bar"
};
client.addSoapHeader(soapHeader);
According with the documentation , for aggregate HTTP Headers, you can put headers, example code:
soap.createClient(url,
function (err, client) {
if(err){
console.log(err);
} else{
console.log(client.describe())
var soapHeaders = {
'Channel':'PB',
'RqUID':'1987'
}
client.addHttpHeader('<nameH1>', 'valueH1');
client.addHttpHeader('<nameH2>', 'valueH2');
//then, continue calling the soap operation
}
Reading through the README for node-soap, if what you're trying to do is not WS-Security (I have no idea because I stay far away from SOAP), then you're going to have to file an issue with the author, because I see no way to set custom headers according to the documentation.
If it is WS-Security, then follow the instructions on this part of the README.
soap = require('soap')
parseString = require('xml2js').parseString
soap.createClient('https://api.bingads.microsoft.com/Api/Advertiser/AdIntelligence/v9/AdIntelligenceService.svc?wsdl', function(err, client) {
var soapHeader = {
'AuthenticationToken': process.argv[2],
'DeveloperToken': process.argv[3],
'CustomerId': process.argv[4],
'CustomerAccountId': process.argv[5]
};
client.addSoapHeader(soapHeader);
client.SuggestKeywordsFromExistingKeywords({Keywords: ["Hello world"]}, function(err, result) {
console.log(result.body);
});
});
This won't work. The reply is invalid login credentials. The same credentials work fine with SOAPUI. So, the format of sending the login credentials mentioned in the other answers must be wrong.
This worked for me. The create client method needs the wsdl_header to retrieve the wsdl definition. Once it is created, you need to set the basic auth security.
var url = 'your WSDL url';
var auth = "Basic " + new Buffer("username" + ":" + "password").toString("base64");
soap.createClient( url,{ wsdl_headers: {Authorization: auth} }).then(
function(client){
client.setSecurity(new soap.BasicAuthSecurity('rflhconfort_ws', '6syqxje9'));
client.your_Method(args);
}
I had the same issue and i resolved it in the below is what worked for me
My wsdl with which i inserted data using SOAPUI Client(To see what are the fields required)
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:yourUrn">
<soapenv:Header>
<urn:AuthenticationMethod>
<urn:userName>username</urn:userName>
<urn:password>password</urn:password>
</urn:AuthenticationMethod>
</soapenv:Header>
<soapenv:Body>
<urn:SoapFunctionToCall>
<urn:Field1>Text</urn:Field1>
<urn:Field2>Text</urn:Field2>
<urn:Field3>Text</urn:Field3>
<urn:Field14>Text</urn:Field4>
<urn:Field5>Text</urn:Field5>
<urn:Field6>Text</urn:Field6>
</urn:SoapFunctionToCall>
</soapenv:Body>
</soapenv:Envelope>
Below is the method i called in node
function createSoapEntry(){
let url = "your wsdl url"
var credentials = {
AuthenticationMethod:{
userName: "username",
password: "password"
}
}
let args = {
Field1:"Text",
Field2:"Text",
Field3:"Text",
Field4:"Text",
Field5:"Text",
Field6:"Text"
}
soap.createClient(url, function (err, client){
client.addSoapHeader(credentials)
client.SoapFunctionToCall(args, function (err, res) {
if (err) {
console.log("Error is ----->" + err)
} else {
console.log("Response is -----> " + res)
}
})
})
}

Resources