How to generate SharedKeyLite for Azure Table Storage REST request - javascript

I'm trying to call Azure Table Storage using Postman but keep getting :
Server failed to authenticate the request. Make sure the value of
Authorization header is formed correctly including the signature.
The code I am using for the pre-call script in Postman is as follows:
var storageAccount = "**mystorageaccount**";
var accountKey = "**mystoragekey**";
var date = new Date();
var UTCstring = date.toUTCString();
var data = date + "\n" + "/**mystorageaccount**/**mytable**"
var encodedData = unescape(encodeURIComponent(data));
var hash = CryptoJS.HmacSHA256(encodedData, accountKey);
var signature = hash.toString(CryptoJS.enc.Base64);
var auth = "SharedKeyLite " + storageAccount + ":" + signature;
postman.setEnvironmentVariable("auth", auth);
postman.setEnvironmentVariable("date", UTCstring);
The headers in Postman are as follows:
Authorization : {{auth}}
date : {{date}}
version : 2015-12-11
I am guessing the issue may be with the data variable, but running out of ideas.

The reason you're getting this error is because you're not converting your account key to a buffer. Please change the following line of code:
var hash = CryptoJS.HmacSHA256(encodedData, accountKey);
to
var hash = CryptoJS.HmacSHA256(encodedData, Buffer.from(accountKey, 'base64'));
And you should not get the error.
UPDATE
I also got the same error. Please try the following code:
var storageAccount = "**mystorageaccount**";
var accountKey = "**mystoragekey**";
var date = new Date();
var UTCstring = date.toUTCString();
var data = UTCstring + "\n" + "/**mystorageaccount**/**mytable**"
var encodedData = unescape(encodeURIComponent(data));
var hash = CryptoJS.HmacSHA256(encodedData, CryptoJS.enc.Base64.parse(accountKey));
var signature = hash.toString(CryptoJS.enc.Base64);
var auth = "SharedKeyLite " + storageAccount + ":" + signature;
postman.setEnvironmentVariable("auth", auth);
postman.setEnvironmentVariable("date", UTCstring);
I just tried the code above and was able to list entities in my table.

Related

how solve this appears illegal character when i click two times?

I have this function works well when i click the first time but when i click the second time receive a error in this part
eval("var " + data + "=sinvnword;");
Code:
$('a.play-video').click(function(){
var currentLocation = window.location;
var fullurl = window.location.href;
url = fullurl.split("sendx")[1];
var sinvnword = $('.question-label.active').last().text();
console.log(sinvnword);
var data =url ;
eval("var " + data + "=sinvnword;");
console.log(AXY + "GETIT");
console.log(AXY+"mor");
console.log(AXY + "muerte");
});
Rather than using eval to create dynamic variable names, simply use dynamic property names:
var data = {};
$('a.play-video').click(function(){
var currentLocation = window.location;
var fullurl = window.location.href;
var key = fullurl.split("sendx")[1];
var sinvnword = $('.question-label.active').last().text();
console.log(sinvnword);
data[key] = sinvnword;
console.log(AXY + "GETIT");
console.log(AXY+"mor");
console.log(AXY + "muerte");
});

How to send an email with a PDF through a script inside google spreadsheets?

The script just works as I want, I didn't develop it, I forgot the author's site, sorry if I don´t mention he/she.
The big problem is that I´m unable or I can't figure out how can I send an email with the PDF created through the script, I don't want to sent it in Zip format and if you release, the PDF file name´s change every time you use the spreadsheet, here I leave the code:
function spreadsheetToPDF(){
var key = '1hBbCnmca_wx4wbQx93Vf4d9cfUwGbFSP9hKgv9Qu7Vk'; //docid
var index = 0; //sheet gid / number
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ActiveSheet = ss.getSheetByName('Sheet 1');
var timestamp = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'-'HHmm");
var plainonum = ActiveSheet.getRange("C5").getValue(); //order number
var supp_name = ActiveSheet.getRange("C12").getValue(); //supplier
var onum = ('0000' + plainonum ).slice(-4); //sets leading zeros to order number
var description = ActiveSheet.getRange("C18").getValue(); //description
var email = ActiveSheet.getRange("D1").getValue(); //email
var name = 'Order-' + onum +'-' + supp_name + '-' + description + '-' + timestamp + '.pdf'; //makes pdf filename
SpreadsheetApp.flush(); //ensures everything on spreadsheet is "done"
//make the pdf from the sheet
var theurl = 'https://docs.google.com/spreadsheets/d/'
+ key
+ '/export?exportFormat=pdf&format=pdf'
+ '&notes=false'
+ '&size=letter'
+ '&portrait=true'
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false&pagenumbers=false'
+ '&gridlines=false'
+ '&fzr=false' // do not repeat frozen rows on each page
+ '&gid='
+ index; //the sheet's Id
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdf = docurl.getBlob().setName(name).getAs('application/pdf');
//save the file to folder on Drive
var fid = '0B6iePPHdQRoxQVB3eERrb1c3MUE';
var folder = DriveApp.getFolderById(fid);
folder.createFile(pdf);
var pfd = DriveApp.getFileById(pdf.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:name,content:pfd, mimeType:'application/pdf'};
// Here I need to send the email
// GmailApp.sendEmail(email, "The subject", "The body content") // AND The PDF File witch I can´t attach
//Show a Popup with a message that a file was created inside a folder
SpreadsheetApp.getUi().alert('New document created in' + ' ' + folder);
}
After getting the file from drive using the DriveApp.getFolderById(id), you may then send it as an attachment using MailApp.sendEmail(recipient, subject, body, options).
Here's the sample code that you can try:
// Send an email with two attachments: a file from Google Drive (as a PDF) and an HTML file.
var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
var blob = Utilities.newBlob('Insert any HTML content here', 'text/html', 'my_document.html');
MailApp.sendEmail('mike#example.com', 'Attachment example', 'Two files are attached.', {
name: 'Automatic Emailer Script',
attachments: [file.getAs(MimeType.PDF), blob]
});
Solution given in this SO post might also help.
As I suspected, I was emailing only the name of the file but without the content, so I made a little variation to the var under the folder creation:
var archivo = docurl.getBlob().getAs('application/pdf').getBytes();
// Create a PDF from the active sheet, save it under a specific directory and send the PDF by mail
function spreadsheetToPDF(){
var key = 'abcdefghijk1234567890'; //docid (actual spreadsheet)
var index = 0; //sheet gid / number
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ActiveSheet = ss.getSheetByName('Hoja 1');
var timestamp = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'-'HHmm");
var plainonum = ActiveSheet.getRange("C5").getValue(); //order number
var supp_name = ActiveSheet.getRange("C12").getValue(); //supplier
var onum = ('0000' + plainonum ).slice(-4); //sets leading zeros to order number
var description = ActiveSheet.getRange("C18").getValue(); //description
var correo = ActiveSheet.getRange("D1").getValue(); //correo electrónico
var name = 'Order-' + onum +'-' + supp_name + '-' + description + '-' + timestamp + '.pdf'; //makes pdf filename
SpreadsheetApp.flush(); //ensures everything on spreadsheet is "done"
//make the pdf from the sheet
var theurl = 'https://docs.google.com/spreadsheets/d/'
+ key
+ '/export?exportFormat=pdf&format=pdf'
+ '&size=A4'
+ '&portrait=true'
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false&pagenumbers=false'
+ '&gridlines=false'
+ '&fzr=false' // do not repeat frozen rows on each page
+ '&gid='
+ index; //the sheet's Id
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdf = docurl.getBlob().setName(name).getAs('application/pdf');
//save the file to folder on Drive
var fid = 'abcdefghij1234567890';
var folder = DriveApp.getFolderById(fid);
folder.createFile(pdf);
//get the file, name and content to send it by email
var archivo = docurl.getBlob().getAs('application/pdf').getBytes();
var attach = {fileName:name,content:archivo, mimeType:'application/pdf'};
// Send email with the PDF attached
GmailApp.sendEmail(correo, "The subject", "The body content", {attachments:[attach]});
//Show a Popup with a message that a file was created inside a folder
SpreadsheetApp.getUi().alert('Nuevo Documento creado en el folder' + ' ' + folder);
}

Azure Account Shared Access Signiture

I am trying to construct an Account level Shared Access Signiture so my client can access all containers in a storage account. I am following these docs Account SAS. It seems straight forward enough but I keep getting the following error message:
"Signature did not match. String to sign used was accountname\nrl\nb\nsc\n\n2016-10-09\n\n\n2015-04-05\n".
My parameters are identical so I suspect it has something to do with how I am hashing the String to Sign. Below is how I construct the token.
var crypto = require('crypto');
var accountName = 'accountname';
var accountKey = 'tH37FTlG3TUT86caMrt2y5kOzof8nFqqA6spzg6r7HPRojE1zDiLJD/xE4oLFDh4RNqAmymvlV7fm8W4SF8cJg==';
var signedPermissions = "sp=rl";
var signedServcies = "ss=b";
var signedResourceType = "srt=sc";
var signedExpiry = "se=2016-10-09";
var signedVersion = "sv=2015-04-05";
var stringToSign = accountName + "\n" + signedPermissions + "\n" + signedServcies + "\n" + signedResourceType + "\n" + signedExpiry + "\n" + signedVersion + "\n";
var hmacsha256 = crypto.createHmac('sha256', accountKey).update(stringToSign).digest('base64');
var token = signedPermissions + "&" + signedServcies + "&" + signedResourceType + "&" + signedExpiry + "&" + signedVersion + "&sig=" + hmacsha256;
I have tried using crypto-js as well but to no avail. The final URL used to access a blob in a container is...
"https://accountname.blob.core.windows.net/containername/blobName?srt=sc&se=2016-10-09&api-version=2015-04-05&sp=rl&ss=b&sv=2015-04-05&sig=IFD2wyfRAsHGU5IFg3RbwSJW6tRE0m0%2FxgAYvJ%2FmnEk%3D"
I have been trying for days and really would appreciate knowing what I'm doing wrong. Thanks.
Benzene, for stringToSign, the value should NOT has the parameter name?
var signedPermissions = "rl";
var signedServcies = "b";
var signedResourceType = "sc";
var signedExpiry = "2016-10-09";
var signedVersion = "2015-04-05";
Please try the following (code shamelessly taken from Azure Storage Node.js library):
var hmacsha256 = crypto.createHmac('sha256', new Buffer(accountKey, 'base64')).update(stringToSign, 'utf-8').digest('base64');

Excel Export getting error: Failed - Network Error on large exports

I'm using this code to export tables off of a web page.
This snippet of code works fine when I export tables of < 1000 rows or so, but when I try to export larger tables I get the error: Failed Network Error. This happens in chrome. It doesn't do anything in IE (surprise).
Is it a memory issue? Any ideas how I can export large tables without running into issues?
Thanks for any help
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = month + "." + day + "." + year + "_" + hour + "." + mins;
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('datatable');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'MachineReport_' + postfix + '.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
I had faced the same problem. This help me solved it. Please try replace:
a.href = data_type + ', ' + table_html;
With:
xData = new Blob([table_html], { type: 'text/csv' });
var xUrl = URL.createObjectURL(xData);
a.href = xUrl;
No answers, but after research it seems to be part of the 2meg limit Chrome imposes when trying to execute this script. I do not know of a work around.

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