Azure Log Analytics POST / Search Query in Plain HTML using javascript - javascript

I want to Upload an event to Azure LOG Analytics and Retrieve an event using plain JavaScript with XMLHTTPRequest or JQuery rest .
1.Using powershell invoke-webrequest, i am able to Upload the event but not through the below request from html
2. Need help in retrieving an event from Azure Log Analytics RestApi
for the first one Here is the sample code HTTP405: BAD METHOD - The HTTP verb used is not supported.
var strBody = {
"Hostname": "sdfsfsdf",
"Customer": "sdfsfdsfdsf",
"RoundTripLatencyInMs": 67,
};
debugger;
customerId = "xxxxxxxxxxxxxxx";
sharedkey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
logType = "xxxxxxxxx";
TimeStampField = "YYYY-MM-DDThh:mm:ssZ";
// encodebody = stringToUtf16ByteArray(JSON.stringify(strBody).toString('utf8'));//encode_utf8(JSON.stringify(strBody));
str = strBody;
var byteArray = [];
for (var i = 0; i < str.length; i++)
if (str.charCodeAt(i) <= 0x7F)
byteArray.push(str.charCodeAt(i));
else {
var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
for (var j = 0; j < h.length; j++)
byteArray.push(parseInt(h[j], 16));
}
// return byteArray;
encodebody = byteArray;
method = 'POST';
resource = '/api/logs';
//contentType = 'application/json; charset=utf-8';
var d =new Date();
msdate = d.toUTCString(); //'Thu, 14 Jul 2017 06:35:52 GMT';
contentLength = encodebody.length;
//Signature
xHeaders = "x-ms-date:" + msdate;
stringToHash = method + "\n" + contentLength + "\n" + xHeaders + "\n" + resource;
//message=stringToHash;
var hash = CryptoJS.HmacSHA256(stringToHash, sharedkey);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
// document.write(hashInBase64);
//authorization = 'SharedKey ' + customerId +':'+ hashInBase64 ;
signature = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(CryptoJS.enc.Utf8.parse(stringToHash), CryptoJS.enc.Base64.parse(sharedkey)));
authorization = 'SharedKey ' + customerId + ':' + signature;
uri = "https://" + customerId + ".ods.opinsights.azure.com" + resource + "?api-version=2016-04-01";
var myHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
debugger;
$.ajax({
url: uri,
type: 'POST',
success: function (data) {
//do something to data
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "SharedKey " + customerId + ":" + signature);
xhr.setRequestHeader('x-ms-date', msdate);
xhr.setRequestHeader('x-ms-version', '2014-02-14');
xhr.setRequestHeader('Accept-Charset', 'UTF-8');
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
//xhr.setRequestHeader('Accept', 'application/json;odata=nometadata');
xhr.setRequestHeader("Log-Type", logType);
xhr.setRequestHeader("time-generated-field", TimeStampField);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//xhr.setRequestHeader('DataServiceVersion', '3.0;NetFx');
//xhr.setRequestHeader('MaxDataServiceVersion', '3.0;NetFx');
},
datatype:'json',
//contentType: 'application/json',
data:encodebody,
error: function (rcvData) {
console.log("ERRor");
console.log(rcvData);
}
});
Any pointers will be helpfull

As you made a REST call from browser side using javascript, the browser would first send an HTTP request by the OPTIONS method to the resource to look for CORS headers. See Preflighted requests. And Log Analytics REST API doesn't allow the OPTIONS HTTP verb. It means that the API doesn't support CORS. So, it raises your issue.
So, you should call the REST API by using server side language like PHP, Python, Node.js, etc.

Related

Cryptopia API in Google Sheet - Signature does not match request parameters

I am trying to connect to Cryptopia API to get my balance in Google Sheet and I can't make it work. The error I am currently getting is:
Signature does not match request parameters
API Private Documentation
My code:
var key1 = "API_KEY";
var secret1 = "API_SECRET";
var nonce = Math.floor(new Date().getTime()/1000);
var params = {"Currency" : "BTC"};
var url = 'https://www.cryptopia.co.nz/api/GetBalance';
var requestContentBase64String = Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, JSON.stringify(params), Utilities.Charset.UTF_8)); // Added
var signature = key1 + "POST" + encodeURIComponent(url).toLowerCase() + nonce + requestContentBase64String; // Modified
var hmacsignature = Utilities.base64Encode(Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, signature, Utilities.base64Decode(secret1), Utilities.Charset.UTF_8)); // Modified
var header_value = "amx " + key1 + ":" + hmacsignature + ":" + nonce;
var headers = {
"Authorization": header_value,
"Content-Type": 'application/json; charset=utf-8'
//"Content-Length" : Utilities.newBlob(JSON.stringify(params)).getBytes().length // Added
};
var options = {
"method": 'POST',
"headers": headers,
"payload": JSON.stringify(params),
"contentLength": JSON.stringify(params).length
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response)
return JSON.parse(response.getContentText());
There is one more thread regarding the same issue on stackoverflow but without correct answer.
Thank you

SVG to PNG to AJAX API post

I have a rather large and complex code of SVG that generates using JavaScript and jQuery dynamically based on the pages information.
I then have an AJAX post save.
What am I failing to do to convert this to post the image data properly?
var canvas = $("#canvas")[0];
var string= canvas.toDataURL("image/png");
base64=string.replace("data:image/png;base64,", "");
var rid = kRid || "";
var fileN = " Product " + rid + ".png";
var req = "";
req += "<qdbapi>";
req += "<field fid='323' filename='" + fileN + "'>" + base64 + "</field>";
req += "</qdbapi>";
$.ajax({
type: "POST",
contentType: "text/xml",
dataType: "xml",
processData: false,
//url altered
url: "https://removed.quickbase.com/db/removedDBID?act=API_EditRecord&rid=" + rid,
data: req,
success: function(responce) {
//auto reload page
var str = window.location.href;
setTimeout(function() {
window.location.href = str;
}, 5000);
}
})
The idea came from this snippet of code that I used else ware to get current PNG files and move them:
$.get(url, function(xml) {
var promises = [];
$("record", xml).each(function() {
var url = $("f#9 url", this).text();
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var arrayBuffer = xhr.response;
var base64 = btoa([].reduce.call(new Uint8Array(arrayBuffer), function(p, c) {
return p + String.fromCharCode(c)
}, ''))
var req = "";
req += "<qdbapi>";
req += "<field fid='6' filename='" + name + "'>" + base64 + "</field>";
req += "<field fid='54' >" + Rid + "</field>";
req += "<field fid='44' >" + comment + "</field>";
req += "</qdbapi>";
... then the AJAX post.
I do not have access to do this via PHP.
(Posted on behalf of the OP).
I forgot to add == to mark the end of the file so:
var string= canvas.toDataURL("image/png");
string+="==";
base64=string.replace("data:image/png;base64,", "");
and huzza it works...

How to use publish_action permission of facebook api?

I want to post base64 encoded images in facebook. Below is my code
function postImageToFacebook(authToken, filename, mimeType, imageData, message) {
// this is the multipart/form-data boundary we'll use
var boundary = '----ThisIsTheBoundary1234567890';
// let's encode our image file, which is contained in the var
var formData = '--' + boundary + '\r\n'
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
for (var i = 0; i < imageData.length; ++i) {
formData += String.fromCharCode(imageData[i] & 0xff);
}
formData += '\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += message + '\r\n'
formData += '--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true);
xhr.onload = xhr.onerror = function () {
console.log(xhr.responseText);
};
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
if(!xhr.sendAsBinary){
xhr.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
}
xhr.sendAsBinary(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('Your image has been successfully shared');
}
}
};
var data = yourDesigner.getProductDataURL();
var encodedPng = data.substring(data.indexOf(',') + 1, data.length);
var decodedPng = Base64Binary.decode(encodedPng);
// var decodedPng = dataURItoBlob(test,"png");
FB.getLoginStatus(function (response) {
var request = {};
if (response.status === "connected") {
request = postImageToFacebook(response.authResponse.accessToken, "test", "image/png", decodedPng, "www.captivations.com.au");
} else if (response.status === "not_authorized") {
FB.login(function (response) {
request = postImageToFacebook(response.authResponse.accessToken, "test", "image/png", decodedPng, "www.captivations.com.au");
}, {scope: "publish_actions"});
} else {
FB.login(function (response) {
request = postImageToFacebook(response.authResponse.accessToken, "test", "image/png", decodedPng, "www.captivations.com.au");
}, {scope: "publish_actions"});
}
});
I can post images when i logged into my facebook account . But when i tried to post the images from other accounts i got following error
"error": {
"message": "(#200) Requires extended permission: publish_actions",
"type": "OAuthException",
"code": 200,
"fbtrace_id": "EAcb5VG/eFS"
}
I think its permission issue of the facbook api. Can you help me on managing "publish action" permission of facebook?
From https://developers.facebook.com/docs/facebook-login/permissions:
The "publish_actions" provides access to publish Posts, Open Graph actions, achievements, scores and other activity on behalf of a person using your app.
Your app does not need to request the publish_actions permission in order to use the Feed Dialog, the Requests Dialog or the Send Dialog.
If you use the "publish_actions" permission in another way you have to requests Facebook to review how your app uses the "publish_actions" permission.

How can access the data recieved from API outside of this function

I have used node.js and request.js to access form information from our email services API. With the console.log in the function I am able to see all the info that I need. I have tried to access it outside of the function with dot notation(request.missionStatement) which I don't think is right. I want to be able to display this on a page within an express.js app.
var request = require('request');
// Basic Authentication credentials
var username = "user";
var password = "password";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
// Search for Custom Data Objects Affiliate Falculty form
request(
{
url : "url to api",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
var parsedData = JSON.parse(body);//convert text from API to JSON file
var missionStatement = [];
for (var i = 0; i < parsedData.elements.length ; i++) {
var individualStatement = "";
//Get text submission from form and push into array
individualStatement += (parsedData.elements[i].fieldValues[4].value + ", " + parsedData.elements[i].fieldValues[2].value + " " + parsedData.elements[i].fieldValues[3].value + ", " + parsedData.elements[i].fieldValues[0].value);
missionStatement.push(individualStatement);
};
console.log(missionStatement)
}
);
The variable missionStatement is a local variable declared inside an anonymous function passed as an argument to the request function, and thus it is inaccessible once the anonymous function returns. You must save your result elsewhere. Try something like this:
var request = require('request');
// Basic Authentication credentials
var username = "user";
var password = "password";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
var result;
// Search for Custom Data Objects Affiliate Falculty form
request(
{
url : "url to api",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
var parsedData = JSON.parse(body);//convert text from API to JSON file
var missionStatement = [];
for (var i = 0; i < parsedData.elements.length ; i++) {
var individualStatement = "";
//Get text submission from form and push into array
individualStatement += (parsedData.elements[i].fieldValues[4].value + ", " + parsedData.elements[i].fieldValues[2].value + " " + parsedData.elements[i].fieldValues[3].value + ", " + parsedData.elements[i].fieldValues[0].value);
missionStatement.push(individualStatement);
};
result = missionStatement;
displayResult();
});
function displayResult() {
console.log(result);
}
Your missionStatement will now be saved in result, but only after the anonymous callback to request() has been called (when the actual request is finished).

oauth 1.0 -invalid signature GetRequestToken for Google

I could not find any active Oauth 1.0 support by Google as it has already been deprecated.
But as I want to access Gmail data,I am bound to use Oauth 1.0
So I have been trying since 2 days to get the RequestToken for my Google Application and I am getting the invalid signature error.
My base-string matches with the debug-string returned by google.
I have tried using both HMAC-SHA1 and RSA-SHA1 and my keys are correct.
(I have even tried using both token and secret as anonymous which Google recommends for non-registered applications.)
Could it be something due to wrong nonce or due to some percent-encoding issue.
The same method worked fine for Twitter.
I am also pasting my code below and would be glad if someone could help or point me to the right forum.
$('#GMAIL_BUTTON').click(function () {
//oauth1 approach similar to twitter
var requestUrl = "https://www.google.com/accounts/OAuthGetRequestToken";
var scope = "https://mail.google.com/";
var clientID = "anonymous";
var clientSecret = "anonymous";
var rsakey = "MIICblahblahblah";
var timestamp = Math.round(new Date().getTime() / 1000.0);
var nonce = Math.random();
var sigBaseStringParams = "oauth_consumer_key=" + clientID;
sigBaseStringParams += "&" + "oauth_nonce=" + nonce;
sigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
sigBaseStringParams += "&" + "oauth_timestamp=" + timestamp;
sigBaseStringParams += "&" + "scope=" + encodeURIComponent(scope);
var sigBaseString = "GET&";
sigBaseString += encodeURIComponent(requestUrl) + "&" + encodeURIComponent(sigBaseStringParams) + "\n" + "\n";
requestUrl += "?scope=https://mail.google.com/";
var keyText = encodeURIComponent(clientSecret) + "&";
//var keyText = rsakey;
var keyMaterial = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(keyText, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
var macAlgorithmProvider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.openAlgorithm("HMAC_SHA1");
var key = macAlgorithmProvider.createKey(keyMaterial);
//var keyMaterial = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(rsakey);
//var macAlgorithmProvider = Windows.Security.Cryptography.Core.AsymmetricKeyAlgorithmProvider.openAlgorithm("RSASIGN_PKCS1_SHA1");
//var key = macAlgorithmProvider.importKeyPair(keyMaterial);
var tbs = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(sigBaseString, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
var signatureBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.sign(key, tbs);
var signature = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(signatureBuffer);
var dataToPost = "OAuth oauth_consumer_key=\"" + clientID + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + timestamp + "\", oauth_signature=\"" + encodeURIComponent(signature) + "\", oauth_version=\"1.0\"";
var response = sendGetRequest(requestUrl, dataToPost, null);
});
And the SendGetRequest method is -
function sendGetRequest(url, authzheader, params) {
try {
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.setRequestHeader("Authorization", authzheader);
request.send(params);
return request.responseText;
} catch (err) {
WinJS.log("Error sending request: " + err, "Web Authentication SDK Sample", "error");
}
}
I couldn't find any glaring errors in your code, but you'll probably have a much easier time using Google's OAuth 2 for client-side apps library at https://developers.google.com/accounts/docs/OAuth2UserAgent. Further, you may want to use the atom feed scope (https://mail.google.com/mail/feed/atom)--you can give it and other scopes a try at https://code.google.com/oauthplayground/.

Categories