Azure Account Shared Access Signiture - javascript

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');

Related

I Got A Problam In Whatsapp Sharing Using Javascript

i have a button when i click on this button then whatsapp opens and when i click in a chat and want to send massege then all things come properly but full url not come because & included in my url.
My Url is like this
www.yoururl.com?1st=1&2nd=2&3rd=2&4th=1&5th=2&6th=2&7th=2&8th=2&9th=2&10th=2&share=share&name=s
But sharing in whatsapp then comes only
www.yoururl.com?1st=1
when i remove first & Then url is comes
www.yoururl.com?1st=12nd=2
so i want to share full url with &
Here Is javascript code Code
var url1 = "?1st=" + encodeURIComponent(selectedOption1) + "&2nd=" + encodeURIComponent(selectedOption2) + "&3rd=" + encodeURIComponent(selectedOption3) + "&4th=" + encodeURIComponent(selectedOption4) + "&5th=" + encodeURIComponent(selectedOption5) + "&6th=" + encodeURIComponent(selectedOption6) + "&7th=" + encodeURIComponent(selectedOption7) + "&8th=" + encodeURIComponent(selectedOption8) + "&9th=" + encodeURIComponent(selectedOption9) + "&10th=" + encodeURIComponent(selectedOption10);
section3.style.display="none";
section4.style.display="block";
var u = "www.yoururl.com";
var input = document.getElementById("1nameInput").value;
var inputt = document.getElementById("copytxt");
var inputname = "&name=";
var share = "&share=share";
var text = u + url1 + share + inputname + input;
inputt.value = text;
var $whatsApp = $('.whatsapp a');
decorateWhatsAppLink(text, input);
function decorateWhatsAppLink(text, input) {
// Getting user input
var message = "text";
// Opening URL
var url = 'whatsapp://send?text=';
//define the message text
var textttt = 'dare take this Challenge Now ';
//encode the text
//find the link
var $whatsApp = $('.whatsapp a');
//set the href attribute on the link
$whatsApp.attr('href', url + input + textttt + text);
}
url come from text variable
please tell me how to do
use encodeURIComponent on the whole URI not only the parameter values
so that & gets encoded as well ...
foo = "www.yoururl.com?1st=1&2nd=2&3rd=2&4th=1&5th=2&6th=2&7th=2&8th=2&9th=2&10th=2&share=share&name=s"
foo_final = encodeURIComponent(foo);

How to generate SharedKeyLite for Azure Table Storage REST request

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.

Ionic 3, encodeURI with firebase

I need to send a http request to firebase that has this shape
https://db.firebaseio.com/0.json?&orderBy="name"&startAt=query&endAt=query+"\uf8ff"&limitToLast=1&print=pretty&auth=auth_token
My problem is that when I call this request I've a 400 error in console because it replace %22 to question marks and other symbols for \uf8ff and I think firebase doesn't recognize that.
let name = '"name"';
let cod = '"\uf8ff"';
let url = ('https://db.firebaseio.com/0.json?&orderBy=' + encodeURIComponent(name) + '&startAt=' + encodeURIComponent(birraName) + '&endAt=' + encodeURIComponent(birraName) + '+' + encodeURIComponent(cod) + '&limitToLast=1&print=pretty&auth=' + encodeURIComponent(this.idToken));
let response = this.http.get(url).map(res => res.json());
return response;
And then in console
400 Bad Request
Do you have any thougths?
You're missing quotes in your target string to mark string values. If you're searching for nodes starting with Marco, it should be https://db.firebaseio.com/0.json?&orderBy="name"&startAt="Marco"&endAt="Marco\uf8ff"&limitToLast=1&print=pretty&auth=auth_token. Note the double quotes around "Marco" and "Marco\uf8ff".
To build these in your JavaScript:
var url = 'https://db.firebaseio.com/0.json';
url = url + '?orderBy="' + encodeURIComponent(name) + '"';
url = url + "&startAt="' + encodeURIComponent(birraName) + '"';
url = url + "&endAt="' + encodeURIComponent(birraName) + '\uf8ff"';
url = url + '&limitToLast=1&print=pretty';
url = url + '&auth="' + encodeURIComponent(this.idToken))+'"";
Template literals might also be useful to keep this readable:
let url = (`https://db.firebaseio.com/0.json?orderBy=${encodeURIComponent(name)}&startAt=${encodeURIComponent(birraName)}&endAt=${encodeURIComponent(birraName)}${encodeURIComponent(cod)}&limitToLast=1&print=pretty&auth=${encodeURIComponent(this.idToken))}`;

Getting string value from url

var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var userid = url.substring(url.indexOf("#") + 1);
var pass = url.substring(url.indexOf(",") + 1);
console.log("User id: " + userid + "Password: " + pass);
I would like to get string from the URL as value but when I try javascript code like above the value has been given is not what I want. The output that I get from code above is like this:
userid : 123,572ad7f557455 pass : 572ad7f557455
The problem is the userid. How can I display only 123 before the comma?
userid : 123
Simple way is:
var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var urlData = url.substring(url.indexOf("#") + 1);
var userinfo = urlData.split(',');
console.log("User id: " + userinfo[0]);
console.log("Password: " + userinfo[1]);
It's work if your password in param don't have ,.
If you password have ,, use slice to make sure it work:
var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var urlData = url.substring(url.indexOf("#") + 1);
var userinfo = urlData.split(',');
var userId = userinfo[0];
var userinfo = urlData.split(',');
var userPassword = urlData.slice(userId.length + 1, urlData.length); // userId.length + 1 to remove comma
console.log("User id: " + userId);
console.log("Password: " + userPassword);
You could try to set end index for substring() method by url.indexOf(",") like this:
var userid = url.substring(url.indexOf("#") + 1, url.indexOf(","));
N.B. split() may help you if there is no , at password field.
try this:
var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var params = url.substring(url.indexOf("#") + 1).split[','];
var userid = params[0];
var pass = params[1];
console.log("User id: " + userid + "Password: " + pass);
This is not the right way to send params through URL, you need to change it like http://www.example.com/activate_account.html?paramName=123 then you can get your data by param name. And also sending user name and password like this is not good at all, you need to put that in authorization header which will be encoded by base 64 for security purposes.

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