Fitbit API OAuth 1.0a from Titanium (Appcelerator) - javascript

I am using Titanium (Appcelerator) to connect to Fitbit API. (http://www.appcelerator.com)
I have been facing issues of getting "Invalid Signature" when I am trying to request for token.
I'm using HTTPClient from Titanium.Network.HTTPClient class to send the HTTP Request.
I also uses the oauth-1.0a.js library from https://github.com/ddo/oauth-1.0a to assist in getting the nonce and signature value.
Here is the code:
Ti.include('/oauth/ddo/hmac-sha1.js');
Ti.include('/oauth/ddo/enc-base64-min.js');
Ti.include('/oauth/ddo/oauth-1.0a.js');
function FitBitAuth() {
FitBitAuth.signatureMethod = "HMAC-SHA1";
FitBitAuth.clientKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
FitBitAuth.clientSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXX';
FitBitAuth.nonce = "R#nD0m_$tR!nGss";
FitBitAuth.request_token_url = "https://api.fitbit.com/oauth/request_token";
FitBitAuth.callback_url = "http://www.fitbit.com";
}
FitBitAuth.prototype.createConsumerTokenSecretPair = function() {
return OAuth({
consumer : {
public : FitBitAuth.clientKey,
secret : FitBitAuth.clientSecret
},
signature_method : FitBitAuth.signatureMethod
});
};
FitBitAuth.prototype.getRequestTokenRequestData = function() {
return {
url : "https://api.fitbit.com/oauth/request_token",
method : 'POST'
};
};
FitBitAuth.prototype.requestToken = function() {
var oauth = this.createConsumerTokenSecretPair();
var request_data = this.getRequestTokenRequestData();
var authorized_request = oauth.authorize(request_data, '', FitBitAuth.nonce, FitBitAuth.timestamp);
//alert(authorized_request);
return authorized_request;
};
function auth1a() {
var fb = new FitBitAuth();
var rt = fb.requestToken();
var req = Ti.Network.createHTTPClient();
req.open("POST", FitBitAuth.request_token_url);
req.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="'+FitBitAuth.clientKey+'"');
Ti.API.info(rt);
req.send({
oauth_timestamp : rt.oauth_timestamp,
oauth_nonce : rt.oauth_nonce,
oauth_signature : encodeURIComponent(rt.oauth_signature),
oauth_signature_method: rt.oauth_signature_method,
oauth_callback : encodeURIComponent(FitBitAuth.callback_url),
oauth_version : rt.oauth_version
});
req.onload = function() {
var json = this.responseText;
Ti.API.info("HEADER =====================");
Ti.API.info(req.getAllResponseHeaders());
Ti.API.info("END HEADER =================");
Ti.API.info(json);
var response = JSON.parse(json);
//alert(response);
};
}
I have also tried the Fitbit API Debug tool to assist me in getting all the signature right, in fact the signature and base String do match with the one shown by Fitbit API Debug Tool.
However, I keep getting this Invalid Signature, a sample JSON return is shown below:
{"errors":[{"errorType":"oauth","fieldName":"oauth_signature","message":"Invalid signature: rN**ahem**SGJmFwHp6C38%2F3rMKEe6ZM%3D"}],"success":false}
I have also already tested to do the curl way and it works from Terminal, but to no avail it does not give me a success from Titanium.
Any help is appreciated.

I manage to solve it.
I tried to use another way of inserting the parameters through the header.
Such that the setRequestHeader will look like this:
req.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="'+FitBitAuth.clientKey+'", oauth_nonce="'+rt.oauth_nonce+'", oauth_signature="'+rt.oauth_signature+'",...');
Alternatively, we can also use the built in toHeader feature of the oauth library that I'm using:
oauth.toHeader(oauth_data);
The code above will produce the oauth data in key-value pair.
{
'Authorization' : 'OAuth oauth_consumer_key="xxxxxxxxxxxxx"&oauth_nonce="xxxxxx"&...
}
So instead of the long code for setRequestHeader, we can make use of the value of toHeader, code shown below:
req.setRequestHeader('Authorization', oauth.toHeader(oauth_data).Authorization);
Do note that the return result by fitbit is in plaintext.
auth_token=xxxxxxxx&auth_token_secret=xxxxxxxxx&...

Related

How to change Python to Apps Script get api?

I want to change python to apps script in apps script have UrlFetchApp function i'm never use but i'm try
I have code python can get api normally
import requests
url = "https://api.aiforthai.in.th/ssense"
text = 'Have a good day'
params = {'text':text}
headers = {
'Apikey': "xxx-xxx-xxx"
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
so now i'm try code apps script like this but notthing came out ;
Api dashboard call me i'm use api.
maybe wrong payload text?
Detail API
Host
https://api.aiforthai.in.th/ssense
Method
GET/POST
Header
Apikey : xxx-xxx-xxx
Content-Type : application/x-www-form-urlencoded
Parameter
text : text for analysis
This my wrong apps script code
function call_api() {
var url = "https://api.aiforthai.in.th/ssense"
var apiKey = "xxx-xxx-xxx";
var response = UrlFetchApp.fetch(
url,
{
"headers": {
"Apikey": apiKey,
"text": "Have a good day"
}
}
)
Logger.log(response)
}
Thank you for solution.
I believe your goal is as follows.
You want to convert the following python script to Google Apps Script.
import requests
url = "https://api.aiforthai.in.th/ssense"
text = 'Have a good day'
params = {'text':text}
headers = {
'Apikey': "xxx-xxx-xxx"
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
You have already been confirmed that your python script worked fine.
When I saw your python script, text is sent as the query parameter. In this case, how about the folloiwng modification?
Modified script:
function call_api2() {
var text = "Have a good day";
var url = `https://api.aiforthai.in.th/ssense?text=${encodeURIComponent(text)}`;
var apiKey = "xxx-xxx-xxx";
var response = UrlFetchApp.fetch(
url,
{ "headers": { "Apikey": apiKey } }
);
Logger.log(response.getContentText());
}
Note:
If you test the above modified script, when an error occurs, please confirm your apiKey again.
If an error like status code 403 occurs, your URL might not be able to be requested from Google side. I'm worried about this.
Try this instead:
function call_api() {
var url = "https://api.aiforthai.in.th/ssense";
var apiKey = "xxx-xxx-xxx";
var response = UrlFetchApp.fetch(
url,
{
"method" : "GET",
"headers" : {
"Apikey" : apiKey,
"text" : "Have a good day"
}
}
);
Logger.log(response)
}
You can check out the UrlFetchApp documentation for future reference.

How to enable CORS in an Azure App Registration when used in an OAuth Authorization Flow with PKCE?

I have a pure Javascript app which attempts to get an access token from Azure using OAuth Authorization Flow with PKCE.
The app is not hosted in Azure. I only use Azure as an OAuth Authorization Server.
//Based on: https://developer.okta.com/blog/2019/05/01/is-the-oauth-implicit-flow-dead
var config = {
client_id: "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx",
redirect_uri: "http://localhost:8080/",
authorization_endpoint: "https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/authorize",
token_endpoint: "https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token",
requested_scopes: "openid api://{tenant-id}/user_impersonation"
};
// PKCE HELPER FUNCTIONS
// Generate a secure random string using the browser crypto functions
function generateRandomString() {
var array = new Uint32Array(28);
window.crypto.getRandomValues(array);
return Array.from(array, dec => ('0' + dec.toString(16)).substr(-2)).join('');
}
// Calculate the SHA256 hash of the input text.
// Returns a promise that resolves to an ArrayBuffer
function sha256(plain) {
const encoder = new TextEncoder();
const data = encoder.encode(plain);
return window.crypto.subtle.digest('SHA-256', data);
}
// Base64-urlencodes the input string
function base64urlencode(str) {
// Convert the ArrayBuffer to string using Uint8 array to convert to what btoa accepts.
// btoa accepts chars only within ascii 0-255 and base64 encodes them.
// Then convert the base64 encoded to base64url encoded
// (replace + with -, replace / with _, trim trailing =)
return btoa(String.fromCharCode.apply(null, new Uint8Array(str)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// Return the base64-urlencoded sha256 hash for the PKCE challenge
async function pkceChallengeFromVerifier(v) {
const hashed = await sha256(v);
return base64urlencode(hashed);
}
// Parse a query string into an object
function parseQueryString(string) {
if (string == "") { return {}; }
var segments = string.split("&").map(s => s.split("="));
var queryString = {};
segments.forEach(s => queryString[s[0]] = s[1]);
return queryString;
}
// Make a POST request and parse the response as JSON
function sendPostRequest(url, params, success, error) {
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function () {
var body = {};
try {
body = JSON.parse(request.response);
} catch (e) { }
if (request.status == 200) {
success(request, body);
} else {
error(request, body);
}
}
request.onerror = function () {
error(request, {});
}
var body = Object.keys(params).map(key => key + '=' + params[key]).join('&');
request.send(body);
}
function component() {
const element = document.createElement('div');
const btn = document.createElement('button');
element.innerHTML = 'Hello'+ 'webpack';
element.classList.add('hello');
return element;
}
(async function () {
document.body.appendChild(component());
const isAuthenticating = JSON.parse(window.localStorage.getItem('IsAuthenticating'));
console.log('init -> isAuthenticating', isAuthenticating);
if (!isAuthenticating) {
window.localStorage.setItem('IsAuthenticating', JSON.stringify(true));
// Create and store a random "state" value
var state = generateRandomString();
localStorage.setItem("pkce_state", state);
// Create and store a new PKCE code_verifier (the plaintext random secret)
var code_verifier = generateRandomString();
localStorage.setItem("pkce_code_verifier", code_verifier);
// Hash and base64-urlencode the secret to use as the challenge
var code_challenge = await pkceChallengeFromVerifier(code_verifier);
// Build the authorization URL
var url = config.authorization_endpoint
+ "?response_type=code"
+ "&client_id=" + encodeURIComponent(config.client_id)
+ "&state=" + encodeURIComponent(state)
+ "&scope=" + encodeURIComponent(config.requested_scopes)
+ "&redirect_uri=" + encodeURIComponent(config.redirect_uri)
+ "&code_challenge=" + encodeURIComponent(code_challenge)
+ "&code_challenge_method=S256"
;
// Redirect to the authorization server
window.location = url;
} else {
// Handle the redirect back from the authorization server and
// get an access token from the token endpoint
var q = parseQueryString(window.location.search.substring(1));
console.log('queryString', q);
// Check if the server returned an error string
if (q.error) {
alert("Error returned from authorization server: " + q.error);
document.getElementById("error_details").innerText = q.error + "\n\n" + q.error_description;
document.getElementById("error").classList = "";
}
// If the server returned an authorization code, attempt to exchange it for an access token
if (q.code) {
// Verify state matches what we set at the beginning
if (localStorage.getItem("pkce_state") != q.state) {
alert("Invalid state");
} else {
// Exchange the authorization code for an access token
// !!!!!!! This POST fails because of CORS policy.
sendPostRequest(config.token_endpoint, {
grant_type: "authorization_code",
code: q.code,
client_id: config.client_id,
redirect_uri: config.redirect_uri,
code_verifier: localStorage.getItem("pkce_code_verifier")
}, function (request, body) {
// Initialize your application now that you have an access token.
// Here we just display it in the browser.
document.getElementById("access_token").innerText = body.access_token;
document.getElementById("start").classList = "hidden";
document.getElementById("token").classList = "";
// Replace the history entry to remove the auth code from the browser address bar
window.history.replaceState({}, null, "/");
}, function (request, error) {
// This could be an error response from the OAuth server, or an error because the
// request failed such as if the OAuth server doesn't allow CORS requests
document.getElementById("error_details").innerText = error.error + "\n\n" + error.error_description;
document.getElementById("error").classList = "";
});
}
// Clean these up since we don't need them anymore
localStorage.removeItem("pkce_state");
localStorage.removeItem("pkce_code_verifier");
}
}
}());
In Azure I only have an App registration (not an app service).
Azure App Registration
The first step to get the authorization code works.
But the POST to get the access token fails. (picture from here)
OAuth Authorization Code Flow with PKCE
Access to XMLHttpRequest at
'https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token' from
origin 'http://localhost:8080' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
Where in Azure do I configure the CORS policy for an App Registration?
Okay, after days of banging my head against the stupidity of Azure's implementation I stumbled upon a little hidden nugget of information here: https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-browser#prerequisites
If you change the type of the redirectUri in the manifest from 'Web' to 'Spa' it gives me back an access token! We're in business!
It breaks the UI in Azure, but so be it.
You should define the internal url with your local host address.
https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/application-proxy-understand-cors-issues
When I first posted, the Azure AD token endpoint did not allow CORS requests from browsers to the token endpoint, but it does now. Some Azure AD peculiarities around scopes and token validation are explained in these posts and code in case useful:
Code Sample
Blog Post

Capture REST calls with Selenium

I run integration test with Selenium as a test runner and webdriver.io javascript library for Selenium API.
My test goes as follows:
I load an html page and click on a button. I want to check if a Get REST call was invoked.
I found a plugin for webdriver.io called webdriverajax that intend to fit to my requirements but it just doesn't work.
Any ideas how do capture rest calls?
You can achieve this by using custom HttpClient class that is out side from selenium code.As far as i know selenium doesn't support this feature.
Assume when you clicked the button it will called a REST service , the URL can be grab from the HTML DOM element.Then you can use your custom code to verify if URL is accessible or not.Then you can decide if your test is pass or failed based on the status code or some other your mechanism.
FileDownloader.java(Sample code snippet)
private String downloader(WebElement element, String attribute) throws IOException, NullPointerException, URISyntaxException {
String fileToDownloadLocation = element.getAttribute(attribute);
if (fileToDownloadLocation.trim().equals("")) throw new NullPointerException("The element you have specified does not link to anything!");
URL fileToDownload = new URL(fileToDownloadLocation);
File downloadedFile = new File(this.localDownloadPath + fileToDownload.getFile().replaceFirst("/|\\\\", ""));
if (downloadedFile.canWrite() == false) downloadedFile.setWritable(true);
HttpClient client = new DefaultHttpClient();
BasicHttpContext localContext = new BasicHttpContext();
LOG.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
if (this.mimicWebDriverCookieState) {
localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies()));
}
HttpGet httpget = new HttpGet(fileToDownload.toURI());
HttpParams httpRequestParameters = httpget.getParams();
httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
httpget.setParams(httpRequestParameters);
LOG.info("Sending GET request for: " + httpget.getURI());
HttpResponse response = client.execute(httpget, localContext);
this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
LOG.info("Downloading file: " + downloadedFile.getName());
FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
response.getEntity().getContent().close();
String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'");
return downloadedFileAbsolutePath;
}
TestClass.java
#Test
public void downloadAFile() throws Exception {
FileDownloader downloadTestFile = new FileDownloader(driver);
driver.get("http://www.localhost.com/downloadTest.html");
WebElement downloadLink = driver.findElement(By.id("fileToDownload"));
String downloadedFileAbsoluteLocation = downloadTestFile.downloadFile(downloadLink);
assertThat(new File(downloadedFileAbsoluteLocation).exists(), is(equalTo(true)));
assertThat(downloadTestFile.getHTTPStatusOfLastDownloadAttempt(), is(equalTo(200)));
// you can use status code to valid the REST URL
}
Here is the reference.
Note: This may not exactly fit into your requirement but you can get some idea and modify it accordingly to fit into your requirement.
Also refer the BrowserMob Proxy using this you can also achieve what you want.
The problem was the webdriver.io version. Apparently, webdriverajax works fine just with webdriver.io v3.x but not with v4.x. I use v4.5.2.
I decide not using a plugin and implement a mock for window.XMLHttpRequest
open and send methods, as follows:
proxyXHR() {
this.browser.execute(() => {
const namespace = '__scriptTests';
window[namespace] = { open: [], send: [] };
const originalOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function (...args) {
window[namespace].open.push({
method: args[0],
url: args[1],
async: args[2],
user: args[3],
password: args[4]
});
originalOpen.apply(this, [].slice.call(args));
};
window.XMLHttpRequest.prototype.send = function (...args) {
window[namespace].send.push(JSON.parse(args[0]));
};
});
}
getXHRsInfo() {
const result = this.browser.execute(() => {
const namespace = '__scriptTests';
return window[namespace];
});
return result.value;
}

JSON url parse returns NaN in Node.js

I have created a URL Shortener web service, which returns JSON, if correct parameters (url) is passed.
Now, since I am learning Node.js, I am trying to create a Node.js wrapper for parsing the data and printing them in console (for now).
I am using http and request module for parsing the JSON data which I received from the url response.
This is my code that prints the data :
var request = require('request');
var http = require('http');
var url = process.argv[2];
var apiUrl = "http://shtr.ml/stats-api.php?url=" + url;
http.get(apiUrl,function(res){
var body = '';
res.on('data',function(chunk)
{
body += chunk;
});
res.on('end',function(){
const resp = JSON.parse(body);
console.log(JSON.stringify(resp));
if(resp.message.toString() == "Success")
{
console.log("Short URL : ",resp.short-url);
console.log("Long URL : ",resp.long-url);
console.log("Creation Date : ",resp.created);
console.log("Total Clicks : ",resp.clicks);
}
else
{
console.log("Stats Error !!");
}
});
}).on('error',function(e){
console.log("Got an error ",e);
});
Now, following is my code output :
C:\node-shtr-module>node index.js http://shtr.ml/ZVFWdk
{"message":"Success","short-url":"http://shtr.ml/ZVFWdk","long-url":"https://github.com/beingadityak/dot-net-mysql","created":"2016-09-27 22:58:06","clicks":"21"}
Short URL : NaN
Long URL : NaN
Creation Date : 2016-09-27 22:58:06
Total Clicks : 21
Why is the resp.short-url returning NaN even though the JSON contains the URL ? Please help.
As always, thanks in advance.
access it using
resp['short-url'] and resp['long-url']

415 Unsupported Media Type error - Domo Connector

So I'm building a connector using the Domo developer tool (they like to call it an IDE) and I just can't seem to get the authentication piece working with their libraries.
Domo uses httprequest library for basic and oauth types of authentication.
I'm having trouble getting token back through Domo, but I can easily do it through a curl or by using the Postman api tool.
Here's the code below:
var client_id = '4969e1ea-71b9-3267-ae7d-4ce0ac6bfa28';
var client_secret = '*****************************';
var user = '*********';
var pass = '*********';
var postData =
{
data: {
'grant_type': 'password',
'username': user,
'password': pass,
'client_id': client_id,
'client_secret': client_secret,
'scope': 'internal'
}
};
var res = httprequest.post('https://rest.synthesio.com/security/v1/oauth/token', postData);
DOMO.log('res: ' + res);
Pleae let me know if you have a different way of approaching this. I've tried to add the header within the postData object itself as well as removing the data variable, leaving the attributes as is, too.
When you past the postData as an object like that, DOMO will run it through JSON.stringify and send the result in the request body.
You can either encode the request body manually or use their httprequest.addParameter function to add them. Try something like this:
var client_id = '4969e1ea-71b9-3267-ae7d-4ce0ac6bfa28';
var client_secret = '*****************************';
var user = '*********';
var pass = '*********';
httprequest.addParameter('grant_type', 'password');
httprequest.addParameter('username', user);
httprequest.addParameter('password', pass);
httprequest.addParameter('client_id', client_id);
httprequest.addParameter('client_secret', client_secret);
httprequest.addParameter('scope', 'internal');
var res = httprequest.post('https://rest.synthesio.com/security/v1/oauth/token');
DOMO.log('res: ' + res);

Categories

Resources