I'm new to Javascript syntax; sorry if this is too basic.
With this query:
const params = queryString.parse(window.location.href)
I am fetching:
{http://localhost:3000/#access_token: "accessToken", refresh_token: "refreshToken"}
and now I can easily do:
const refresh_token = params.refresh_token;
But how do I fetch "accessToken"?
It looks like the hash is malformed JSON. While it'd be parsable by adding a { to the left side, adding "s around word characters before a :, and JSON.parse-ing it:
// const { hash } = window.location;
// const badJSON = '{' + hash.slice(1);
// now, you'll have:
const badJSON = '{' + 'access_token: "accessToken", refresh_token: "refreshToken"}';
const json = badJSON.replace(/\w+(?=:)/g, '"$&"');
const obj = JSON.parse(json);
console.log(obj.access_token);
console.log(obj.refresh_token);
This is extremely awkward, and is a solution to an X/Y problem. It would be much better to fix whatever generates the URL so that its format is in the standard format so you can parse it with URLSearchParams. For example, the URL should be something like
http://localhost:3000/?access_token=accessToken&refresh_token=refreshToken
And then it can be parsed very easily:
const url = 'http://localhost:3000/?access_token=accessToken&refresh_token=refreshToken';
const params = new URLSearchParams(url.match(/\?.*/)[0]);
// in your real code, the above can be replaced with:
// const params = new URLSearchParams(window.location.search);
console.log(params.get('access_token'));
This did the trick:
getHashParams() {
const hashParams = {};
const r = /([^&;=]+)=?([^&;]*)/g;
const q = window.location.hash.substring(1);
let e = r.exec(q);
while (e) {
hashParams[e[1]] = decodeURIComponent(e[2]);
e = r.exec(q);
}
return hashParams;
}
and calling like so:
const params = this.getHashParams();
console.log(params);
logged:
{access_token: "aceessToken", refresh_token: "refreshToken"}
Related
I have been trying to communicate with the private API on kraken. The error I get suggests {"error":["EAPI:Invalid key"]} that the encryption/decryption steps are correct. I have tried creating new keys, does not help. I'm wondering if the 'format' of the signature variable is wrong, even though correct in nature.
function balance () {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("API_read_only");
var key = sheet.getRange("B5").getValue()
var secret = sheet.getRange("B6").getValue()
// (API method, nonce, and POST data)
var path = "/0/private/TradeBalance"
var nonce = new Date () * 1000
var postdata = "nonce=" + nonce
//Algorithms
//Calculate the SHA256 of the nonce and the POST data
// using goolge script lib
// using more succint function from https://stackoverflow.com/questions/16216868/get-back-a-string-representation-from-computedigestalgorithm-value-byte
function SHA_256 (str) {
return Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, str).reduce(function(str,chr){
chr = (chr < 0 ? chr + 256 : chr).toString(16);
return str + (chr.length==1?'0':'') + chr;
},'');
}
var api_sha256 = SHA_256(nonce + postdata)
//Decode the API secret (the private part of the API key) from base64 // need to stringyfy
var base64 = Utilities.base64Decode(secret)
var base64s = Utilities.newBlob(base64).getDataAsString()
//Calculate the HMAC of the URI path and the SHA256, using SHA512 as the HMAC hash and the decoded API secret as the HMAC key
var hamc512_uri = Utilities.computeHmacSha256Signature(path + api_sha256,base64s)
var hamc512_uris = Utilities.newBlob(hamc512_uri).getDataAsString()
//Encode the HMAC into base64
var signature = Utilities.base64Encode(hamc512_uris)
Logger.log(signature)
//An example of the algorithm using the variables shown above is as follows:
//Base64Encode(HMAC-SHA512 of ("/0/private/TradeBalance" + SHA256("1540973848000nonce=1540973848000&asset=xxbt")) using Base64Decode("FRs+gtq09rR7OFtKj9BGhyOGS3u5vtY/EdiIBO9kD8NFtRX7w7LeJDSrX6cq1D8zmQmGkWFjksuhBvKOAWJohQ==") as the HMAC key
//The result is the API-Sign value / signature.
// connect
var url = "https://api.kraken.com" + path;
var options = {
method: 'post',
headers: {
'API-Key': key,
'API-Sign': signature
},
payload: postdata
};
var response = UrlFetchApp.fetch (url, options);
json = response.getContentText ();
Logger.log(json)
}
While I cannot spot what's wrong with your code I faced the same problem as well (thinking I have everything correct but getting a EAPI:Invalid key) with different libraries.
The approach that helped me was:
Take some posted working solution, e.g. https://stackoverflow.com/a/43081507/672008 (in Java)
Check that it really works
Fix the nonce parameter to get a stable HMAC end results
Massage my code until I get then same intermediate & end results
In the end I was successful using this library: https://www.npmjs.com/package/jssha
The code:
import jssha from 'jssha';
const secret = '...';
const nonce = 1642383717038;
const message = '';
const path = '/0/private/Balance';
const data = 'nonce=' + nonce;
const dataHash = new jssha('SHA-256', 'TEXT');
dataHash.update(nonce + data + message);
let utf8Encode = new TextEncoder();
const hmacHash = new jssha('SHA-512', 'UINT8ARRAY', { hmacKey: { value: secret, format: 'B64' } });
hmacHash.update(utf8Encode.encode(path));
hmacHash.update(dataHash.getHash('UINT8ARRAY'));
console.log('hmac', hmacHash.getHash('B64'));
How to convert token to the desired format?
I get token from domain.com on profile.damain.com via urlParams
testConfirm = () => {
if(window.location.href = 'http://localhost:3000') {
const req = localStorage.getItem('accessToken')
JSON.parse(req)
window.location.href = `http://1.localhost:3000?token=${req}`
return true
}
}
Now it comes like this:
{%22token%22:%225ecc2023eb593303e6dea15f5ec775874d656203fdb401805ecc2023eb593303e6dea160%22,%22expiredAt%22:1590522275554,%22timeZone%22:%22Europe/Moscow%22,%22active%22:true}
As needed: {"token":"5eccbf2e94b981c418d675355ec777c894b981c4185100a75eccbf2e94b981c418d67536","expiredAt":1590562990267,"timeZone":"Europe/Moscow","active":true}
Use decodeURI:
let string = '{%22token%22:%225ecc2023eb593303e6dea15f5ec775874d656203fdb401805ecc2023eb593303e6dea160%22,%22expiredAt%22:1590522275554,%22timeZone%22:%22Europe/Moscow%22,%22active%22:true}'
console.log(decodeURI(string))
I’m attempting to authenticate to Coinbase Pro from a Google Script. I’ve managed to do this already in Postman using CryptoJS, but I’m running into issues generating the CB-ACCESS-SIGN signature header. I’ve set up a test using a test key and secret string to figure out the differences between CryptoJS.HmacSHA256 and Utilities.computeHmacSha256Signature, the implementation Google offers, and noticed a difference in parameters: CryptoJS.HmacSHA256 expects a secret as WordArray while Utilities.computeHmacSha256Signature expects a secret as string.
In Postman I'm doing the following to get the wordarray of my apiSecret to pass to CryptoJS.HmacSHA256:
var hash = CryptoJS.enc.Base64.parse(pm.variables.get('apiSecret'));
In my Google script I'm doing the sam
var hash = Utilities.base64Decode(apiSecretB64)
I've tried debugging this with the same secret and message, but I'm getting different results.
My implementation in Postman:
function computeSignature(request) {
const data = request.data;
const method = request.method.toUpperCase();
const path = getPath(request.url);
const body = (method === 'GET' || !data) ? '' : JSON.stringify(data);
const message = timestamp + method + path + body;
const apiSecret = CryptoJS.enc.Base64.parse(pm.variables.get('apiSecret'));
const hash = CryptoJS.HmacSHA256(message, apiSecret);
const hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
return hashInBase64;
}
And my implementation in Google Script:
function computeSignature(request, path, timestamp) {
const data = request.data;
const method = request.method;
const body = (method === 'GET' || !data) ? '' : JSON.stringify(data);
const message = timestamp + method + path + body;
var apiSecret = Utilities.base64Decode(apiSecretB64);
var hash = Utilities.computeHmacSha256Signature(message, apiSecret);
hash = Utilities.base64Encode(hash);
return hash;
}
Does anyone know why I'm getting different results?
I've managed to solve the issue by converting the message from string to a byte array:
function computeSignature(request, path, timestamp) {
const data = request.data;
const method = request.method;
const body = (method === 'GET' || !data) ? '' : JSON.stringify(data);
const message = timestamp + method + path + body;
var apiSecretByteArr = Utilities.base64Decode(apiSecretB64);
var messageByteArr = Utilities.base64Decode(Utilities.base64Encode(message));
var hash = Utilities.computeHmacSha256Signature(messageByteArr, apiSecretByteArr);
return Utilities.base64Encode(hash);
}
There is probably a better way of doing this, but at least the correct signature is now being computed.
I have a following code to decode the Jwt token in Javascript (ref: How to decode jwt token in javascript)
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
function parseJwt(token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
console.log(JSON.parse((atob(base64))))
};
parseJwt(token);
I am getting the payload which I needed from above code
But I am implementing it in node where we dont have "atob" function to decode the base64 encoded string
Seems we need to use Buffer in node. Did my research and came up with below solution which didn't work.
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
function parseJwt(token) {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const buff = new Buffer(base64, 'base64');
const payloadinit = buff.toString('ascii');
const payload = JSON.parse(payloadinit);
console.log(payload)
};
parseJwt(token);
Please let me know if there is any better approach - No libraries(Jwt, or decode-Jwt)
Actually I have tried it in independent environment and above code works like charm for getting Jwt token pay load
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const buff = new Buffer(base64, 'base64');
const payloadinit = buff.toString('ascii');
const payload = JSON.parse(payloadinit);
console.log(payload);
https://repl.it/#Punith/RuralSeveralAdaware
const DecodeJWT= (token) => {
try {
return JSON.parse(atob(token.split('.')[1]));
} catch (e) {
return null;
}
};
simple & easy way
Im trying to convert the C# code found here:
AMX Authorization Header in order to connect to an external API. The C# code works when trying to connect to the external API but when I convert it to a nodeJS solution it doesnt work.
I dont have access to the external C# API so can't update that side but was hoping someone could look at this and see something Im missing or doing wrong:
My nodejs solution:
var request = require('request');
var uuid = require('node-uuid');
var CryptoJS = require('crypto-js');
var URL = "https://urltoexternalAPI.com";
var itemAPPId = "testAPPId";
var APIKey = "testAPIKey";
var requestUri = encodeURIComponent(URL.toLowerCase());
var requestHttpMethod = "GET";
var requestTimeStamp = Math.floor(new Date().getTime() / 1000).toString();
var nonce = uuid.v1().replace(/-/g, '');
//I excluded the content hashing part as the API Im hitting is a GET request with no body content
var signatureRawData = itemAPPId + requestHttpMethod + requestUri + requestTimeStamp + nonce;
var secretKeyByteArray = CryptoJS.enc.Base64.parse(APIKey);
var signature = CryptoJS.enc.Utf8.parse(signatureRawData);
var signatureBytes = CryptoJS.HmacSHA256(signature, secretKeyByteArray);
var requestSignatureBase64String = signatureBytes.toString(CryptoJS.enc.Base64);
request({
url: URL,
headers: {
'Authorization': "amx "+itemAPPId+":"+requestSignatureBase64String+":"+nonce+":"+requestTimeStamp
}
}, function (error, response, body) {
if (response.statusCode != 200) {
console.log("Fail");
} else {
console.log("Success");
}
});
I figured it out! If anyone ever comes across this issue they may find the below helpful:
the following C# code works a little different to nodeJS:
System.Web.HttpUtility.UrlEncode(request.RequestUri.AbsoluteUri.ToLower());
Initially I copied this functionality as is and wrote the nodejs equivalent as such:
var requestUri = encodeURIComponent(URL.toLowerCase());
The encoding of the URL in C# keeps everything in lowercase - for e.g: https:// becomes https%3a%2f%2f - whereas nodeJS uppercases its encoding characters - https%3A%2F%2F - this is what as causing the incorrect hashing.
The solution is to just move the lowercase function to after the encoding has been done on the URL. Like so:
var requestUri = encodeURIComponent(URL).toLowerCase();
Seems rather simple but when trying to replicate the C# solution you may not pick up that the two URL encoders work differently.
Final solution: (updated to crypto thanks to Yoryo)
const fetch = require("node-fetch");
const uuid = require("uuid");
const crypto = require('crypto');
var URL = "https://urltoapi.com";
var itemAPPId = config.itemAPPId;
var APIKey = config.itemAPIKey;
var requestUri = encodeURIComponent(URL).toLowerCase();
var requestHttpMethod = "GET"; //should be dynamic
var requestTimeStamp = Math.floor(new Date().getTime() / 1000).toString();
var nonce = uuid.v1().replace(/-/g, '');
var signatureRawData = itemAPPId + requestHttpMethod + requestUri + requestTimeStamp + nonce;
var key = Buffer.from(APIKey, 'base64');
var requestSignatureBase64String = crypto.createHmac('sha256', key).update(signatureRawData, 'utf8').digest('base64');
const hitExternalAPI = async url => {
try {
const res = await fetch(url, { method: 'GET', headers: { "Authorization": "amx "+itemAPPId+":"+requestSignatureBase64String+":"+nonce+":"+requestTimeStamp } })
.then(res => {
console.log(res.ok);
});
} catch (error) {
console.log("Error",error);
}
};
hitExternalAPI(URL);