Authentication in Node JS soap request - node.js

I am using strong-soap (https://www.npmjs.com/package/strong-soap) for consuming wsdl from Node JS
I have a wsdl with header like below:-
<soapenv:Header>
<wsse:Security xmlns:wsse="http://xyz.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-24" xmlns:wsu="http://secure.xsd">
<wsse:Username>userid</wsse:Username>
<wsse:Password Type="http://pwdtext">password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
I need to add this header information while creating client.
I tried like
var url = "test?wsdl";
soap.createClient(url, {wsdl_headers: {"Username": "username","Password":"password"} }, function(err, client) {
//some logic
});
But every time I was getting soap fault "Authentication Failed".
Any idea what I am doing wrong?
Thanks in advance.

I had the same issue trying to pull data.
my mistake was that in the options of the createClient method is was using headers instead of wsdl_headers
also set the same authentication on the client before any method is called
my code looks as
var url = 'https://datahere?wsdl';
var httpOptions = {
wsdl_headers: {
'Authorization': 'Basic ' + new Buffer('username' + ':' + 'password').toString('base64')
}
};
soap.createClient(url, httpOptions, function(err, client) {
if (err) {
console.log(err.message);
response.status(401).end();
} else {
var requestArgs = {
Method1: 'dummyData',
Method2: ''
};
// client.setSecurity(new soap.BasicAuthSecurity('password', 'password'));
client.addHttpHeader('customHeader1', 'words');
client.addHttpHeader('Authorization', "Basic " + new Buffer('username-app-maker' + ':' + 'password').toString('base64'));
client.GETSOAPMETHOD(requestArgs, function(err, result) {
if (err) {
console.log(err.message);
}
console.log('i found ' + result);
response.send(result);
});
}
});

As mentioned in this answer, wsdl_header object is expecting a key 'Authentication'
So try running the following code:
var url = 'test?wsdl';
var auth = "Basic " + new Buffer("your username" + ":" + "your password").toString("base64");
soap.createClient(url, { wsdl_headers: {Authorization: auth} }, function(err, client) {
});

Related

Binance signature error : "code":-1022,"msg":"Signature for this request is not valid."

I have an issue with binance API signature for their REST API.
When trying to hit the route 'http://binance.com/api/v3/account', I get the following error:
{"code":-1022,"msg":"Signature for this request is not valid."}
I use nodejs and express.
I've seen there is a few questions on this subject but none seems to solve my problem so:
I define keys and urls there
const binanceConfig = {
API_URL: 'http://binance.com',
API_ENDPOINT: '/api/v3/account',
API_KEY: 'API_KEY_EXAMPLE',
API_SECRET: 'API_SECRET_EXAMPLE'
}
I create the signature
function generateSignature() {
const dataQueryString = "recvWindow=60000&timestamp=" + Date.now();
return crypto
.createHmac('sha256', binanceConfig['API_SECRET'])
.update(dataQueryString)
.digest('hex');
}
I define query parameters here
const queryParameters = {
timestamp: Date.now(),
signature: generateSignature(),
recvWindow: '60000',
}
Set the header
var header = {
'Accept': 'Application/json',
'X-MBX-APIKEY': binanceConfig['API_KEY']
};
Create the route to call the API
router.get('/userInfo', (req, res) => {
var stringTest = `timestamp=${queryParameters['timestamp']}`
requestUrl = binanceConfig['API_URL'] + binanceConfig['API_ENDPOINT'] + "?" + stringTest + "&" + "signature=" + queryParameters['signature'] + "&recvWindow=" + queryParameters['recvWindow'];
const options = {
url: requestUrl,
headers: header,
method: 'GET'
}
request(options, (error, response) => {
if (error) { console.log('ERROR'); }
console.log(`Response: ${response.statusCode}`);
console.log(response.body);
});
});
If anyone has any idea why I get this error I'd be gratefull ! Thanks !
You need to have the timestamp and signature (respectively) as the last parameters.
Source

Send a POST request with an image URL? --- Needle library

Trying to figure out the right way to send a RESTful request to an API using the Node.js Needle library. I think everything is right except the code concerning the image URL. No matter how I try to change what it looks like or where I put it, I keep getting an error that says it's an invalid image, but it's not, the URL is fine. So, my guess is my code is wrong and so whatever it thinks is the URL for the image, is probably not the URL (but maybe some other code or code in a location that should be where the body/image URL is).
const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'
// Request parameters.
const params = {
returnFaceId: true,
returnFaceLandmarks: false,
returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}
var options = {
body: '{"url": ' + '"' + imageUrl + '"}',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey
}
}
needle.post(endpoint, params, options, function (err, res, body) {
console.log(`Status: ${res.statusCode}`)
console.log('Body: ', body)
console.log('ERROR: ' + err)
//console.log(res)
})
I have also tried to write the body like a plain ol' object: body = { 'url': imageURL}, but still getting the same error.
Error:
Status: 400
Body: { error: { code: 'InvalidURL', message: 'Invalid image URL.' } }
Here is the API I am trying to call, which has been confirmed to work with other samples:
https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236
For this request you have a combination of parameters:
Some of them as query strings (your 'params')
Some of them as a body payload (your options.body)
Therefore, it seems that you cannot use needle.post directly because it can do query string params OR body param but not both at the same time.
So there are several options:
Set your query string params in the URL field
Change your lib
For the 1st option, here is an example:
const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'
// Request parameters.
const params = {
returnFaceId: true,
returnFaceLandmarks: false,
returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}
// Adding params to query string
serialize = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
endpoint = endpoint + "?" + serialize(params)
// Setting body and options
var body = '{ "url": ' + '"' + imageUrl + '"}'
var options = {
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey
}
}
needle.post(endpoint, body, options, function (err, res, body) {
console.log(`Status: ${res.statusCode}`)
console.log('Body: ', body)
console.log('ERROR: ' + err)
//console.log(res)
})

NODEJS SOAP: Object reference not set to an instance of an object

I got an error:
Object reference not set to an instance of an object
I'm missing something here in the request, but couldn't figure it out. Any help is appreciated.
I tried using soap module as well as strong-soap module, but the same error occurs in both. So it might be the error in request arguments.
Object reference not set to an instance of an object
Code:
"use strict";
var soap = require('strong-soap').soap;
var url = 'http://test.eprabhu.com/Api/Utility.svc?wsdl&UserName=CLIENT';
var requestArgs = {
'UserName': 'CLIENT',
'Password': 'CLIENT12',
'OperatorCode': 2,
'MobileNumber': '9803111111',
'Amount': 100,
'PartnerTxnId': 'P201904220218335187'
};
var options = {
'user-agent': 'sampleTest',
'Content-Type': 'text/xml;charset=UTF-8',
// 'soapAction': 'http://test.eprabhu.com/Api/Utility.svc?wsdl#MobileTopup',
'soapAction': 'http://tempuri.org/IUtility/MobileTopup'
};
soap.createClient(url, options, function(err, client) {
var method = client['MobileTopup'];
method(requestArgs, function(err, result, envelope, soapHeader) {
//response envelope
console.log('Response Envelope: \n' + envelope);
//'result' is the response body
console.log('Result: \n' + JSON.stringify(result));
console.log('Soap Header: \n', soapHeader);
});
});
Any help will be appreciated. Thanks
Change your args to:
var requestArgs = {
MobileTopupRequest: {
UserName: 'CLIENT',
Password: 'CLIENT12',
OperatorCode: 2,
MobileNumber: '9803111111',
Amount: 1,
PartnerTxnId: 'P201904220218335187'
}
};

How to OneDrive API file uploads with node.js?

After a time I finally figure out how to use oAuth2 and how to create a access token with the refresh token. But I can´t find node.js samples for upload files the only thing I found was this module https://www.npmjs.com/package/onedrive-api
But this didn´t work for me because I get this error { error: { code: 'unauthenticated', message: 'Authentication failed' } }
Also if I would enter accessToken: manually with 'xxxxxxx' the result would be the same.
But I created before the upload the access token so I don´t know if this really can be a invalid credits problem. But the funny thing is if I would take the access token from https://dev.onedrive.com/auth/msa_oauth.htm where you can generate a 1h access token the upload function works. I created my auth with the awnser from this question. OneDrive Code Flow Public clients can't send a client secret - Node.js
Also I only used the scope Files.readWrite.all do I maybe need to allow some other scopes ? My code is
const oneDriveAPI = require('onedrive-api');
const onedrive_json_configFile = fs.readFileSync('./config/onedrive.json', 'utf8');
const onedrive_json_config = JSON.parse(onedrive_json_configFile);
const onedrive_refresh_token = onedrive_json_config.refresh_token
const onedrive_client_secret = onedrive_json_config.client_secret
const onedrive_client_id = onedrive_json_config.client_id
// use the refresh token to create access token
request.post({
url:'https://login.microsoftonline.com/common/oauth2/v2.0/token',
form: {
redirect_uri: 'http://localhost/dashboard',
client_id: onedrive_client_id,
client_secret: onedrive_client_secret,
refresh_token: onedrive_refresh_token,
grant_type: 'refresh_token'
}
}, function(err,httpResponse,body){
if (err) {
console.log('err: ' + err)
}else{
console.log('body full: ' + body)
var temp = body.toString()
temp = temp.match(/["]access[_]token["][:]["](.*?)["]/gmi)
//console.log('temp1: ', temp)
temp = temp.join("")
temp = temp.replace('"access_token":"','')
temp = temp.replace('"','')
temp = temp.replace('\n','')
temp = temp.replace('\r','')
//console.log('temp4: ', temp)
oneDriveAPI.items.uploadSimple({
accessToken: temp,
filename: 'box.zip',
parentPath: 'test',
readableStream: fs.createReadStream('C:\\Exports\\box.zip')
})
.then((item,body) => {
console.log('item file upload OneDrive: ', item);
console.log('body file upload OneDrive: ', body);
// returns body of https://dev.onedrive.com/items/upload_put.htm#response
})
.catch((err) => {
console.log('Error while uploading File to OneDrive: ', err);
});
} // else from if (err) { from request.post
}); // request.post({ get access token with refresh token
Can you send me your sample codes please to upload a file to OneDrive API with node.js. Would be great. Thank you
Edit: I also tried to upload a file with this
var uri = 'https://api.onedrive.com/v1.0/drive/root:/' + 'C:/files/file.zip' + ':/content'
var options = {
method: 'PUT',
uri: uri,
headers: {
Authorization: "Bearer " + accesstoken
},
json: true
};
request(options, function (err, res, body){
if (err) {
console.log('#4224 err:', err)
}
console.log('#4224 body:', body)
});
Same code: 'unauthenticated' stuff :/
How about this sample script? The flow of this sample is as follows.
Retrieve access token using refresh token.
Upload a file using access token.
When you use this sample, please import filename, your client id, client secret and refresh token. The detail information is https://dev.onedrive.com/items/upload_put.htm.
Sample script :
var fs = require('fs');
var mime = require('mime');
var request = require('request');
var file = 'c:/Exports/box.zip'; // Filename you want to upload on your local PC
var onedrive_folder = 'samplefolder'; // Folder name on OneDrive
var onedrive_filename = 'box.zip'; // Filename on OneDrive
request.post({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
form: {
redirect_uri: 'http://localhost/dashboard',
client_id: onedrive_client_id,
client_secret: onedrive_client_secret,
refresh_token: onedrive_refresh_token,
grant_type: 'refresh_token'
},
}, function(error, response, body) {
fs.readFile(file, function read(e, f) {
request.put({
url: 'https://graph.microsoft.com/v1.0/drive/root:/' + onedrive_folder + '/' + onedrive_filename + ':/content',
headers: {
'Authorization': "Bearer " + JSON.parse(body).access_token,
'Content-Type': mime.lookup(file),
},
body: f,
}, function(er, re, bo) {
console.log(bo);
});
});
});
If I misunderstand your question, I'm sorry.

Authenticate to JIRA using node-jira module

I need to connect my application to JIRA API, and I found module node-jira, that should help me with that.
However, I'm having problem with authentication.
Here's what I done (nothing special, but for some reason, it doesn't work):
var JiraApi = require('jira').JiraApi;
var jira = new JiraApi('https', '[url to my jira project]', 443, '[username]', '[password]', '2.0.alpha1');
jira.getCurrentUser(function(error, issue) {
if(error){
console.log(error);
return;
}
console.log('success');
});
I receive:
401: Error while getting current user
Any ideas what could go wrong?
After digging into source code, looks like mentioned method isn't making request properly.
It does this.request instead of this.doRequest. I'll submit it to github repo.
This may give you some ideas; it's not a call to get an issue from JIRA, but it shows how to set up an Atlassian API call (from Google Sheets). You just need to plug in the right URL and Endpoint (for a JIRA issue as an example).
function showAtlassian() {
var html = HtmlService.createHtmlOutputFromFile('atlassianform')
.setWidth(200)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(html, 'Atlassian Login');
}
function processAtlassian(myForm) {
var username = myForm.un;
var userpw = myForm.pw;
var myencoded = Utilities.base64Encode(username+":"+userpw);
var headers = {"Authorization" : "Basic " + myencoded};
var options = {
'method': 'get',
"contentType" : "application/json",
"headers": headers,
'muteHttpExceptions': false
}
var ui = SpreadsheetApp.getUi();
url = 'https://---your domain --/wiki/rest/api/user/current';
try {
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response)
var result = ui.alert( 'got valid connection userkey ' + data.userKey );
} catch(error) {
var result = ui.alert( 'invalid user or password: url: '+ url +' err: ' + error.toString());
getatlassian();
}
}
function getatlassian() {
var ui = SpreadsheetApp.getUi();
showAtlassian()
}

Resources