how to Get the access token using oauth.js client library? - javascript

I'm able to get request token verifier from the library(http://oauth.googlecode.com/svn/code/javascript/), But got stuck in getting the access token.. can someone tell me where i'm doing it wrong?
function goForAccessRequest1(verifier){
var url2 = "http://www.google.com/accounts/OAuthGetAccessToken";
var accessor2 = {
token: OAuthToken,
//tokenSecret: OAuthTokenSecret,
signatureMethod : "HMAC-SHA1",
consumerKey : "1010722015153-i8tisqmaqch26b0muqvefbfp3h18m862.apps.googleusercontent.com",
//consumerSecret: "zZp8BsyfIzHJox1rBi8Lq3fm",
};
var message2 = {
action: url2,
method: "POST",
parameters: {
oauth_verifier : verifier,
//scope : "http://www.google.com/calendar/feeds",
}
};
OAuth.completeRequest(message2, accessor2);
var requestBody = OAuth.formEncode(message2.parameters);
//url2 = url2 + '?' + OAuth.formEncode(message2.parameters);
var AccessTokenRequest = new XMLHttpRequest();
AccessTokenRequest.open("POST", url2, true);
AccessTokenRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
AccessTokenRequest.setRequestHeader("Authorization", "OAuth");
AccessTokenRequest.send(requestBody);
AccessTokenRequest.onreadystatechange = function receiveAccessToken(){
if(AccessTokenRequest.readyState == 4){
console.log(AccessTokenRequest.responseText)
}
}
}
I'm getting the error like signature error whenever i try to send the parameters using "GET", and whenevr i send the parameters in POST body, getting the error as "parameters missing"

Related

jQuery .ajax() returning 401 when authentication is correct

I am doing an API request with Upcloud's API server. I sent a request with postman, and it worked just fine, but when I use .ajax(), it returns a 401. I know that the problem isn't the user and pass.
function listIPS(){
var url = 'https://api.upcloud.com/1.2/servers';
function make_basic_auth(name) {
if(name === 'josh'){
var user = 'user';
var pass = 'pass';
}
if(name === 'malcolm'){
var user = 'user';
var pass = 'pass';
}
var tok = user + ':' + pass;
var hash = window.btoa(tok);
console.log("Basic " + hash);
return "Basic " + hash;
}
var auth = make_basic_auth('josh');
$.ajax({
type: "GET",
contentType: 'application/json',
url: "https://api.upcloud.com/1.2/account",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth)
},
success: function(data){
// console.log(data);
}
})
}
This is the error I am recieving:
OPTIONS https://api.upcloud.com/1.2/account 401 (Authorization Required)

HTTP error "AUTH_CSFR_ERROR" with POST to Todoist API via Google Apps Script

I'm attempting to query items out of the Todoist API from Google Apps Script, mimicking a curl POST.
I originally tried to make OAuth2 work, but tokens were not persistent, and I instead opted for the API's method of using individual API tokens to exchange for a valid token.
Using App Script's UrlFetchApp class, I'm attempting to construct at POST request for Todoist's API to retrieve task items, and my getTodoistToken() function is indeed retrieving a valid token response, but the POST command is issuing the following 403:
"error_tag":"AUTH_CSRF_ERROR","error_code":0,"http_code":403,"error_extra":{"access_type":"web_session"},"error":"AUTH_CSRF_ERROR"}
Can anyone recommend a solution? Thanks so much, code below:
function getTodoistToken() {
var url = "https://todoist.com/api/access_tokens/migrate_personal_token";
var data = {
"client_id": "[my unique client_id]",
"client_secret": "[my unique client_secret]",
"personal_token":"[my API token from Todoist dashboard]",
"scope": "data:read"
};
var payload = JSON.stringify(data);
var headers = {
"Content-Type":"application/json",
};
var options = {
"method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
return(data.access_token);
}
function getTodoistTasks(){
var apiURL = "https://todoist.com/API/v7/sync";
var data = {
"token" : getTodoistToken(),
"sync_token" : '*',
"resource_types" : '["items"]'
};
var payload = JSON.stringify(data);
Logger.log(payload);
var headers = {
"Content-Type":"application/json",
};
var options = {
"method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload,
"muteHttpExceptions" : true
};
var response = UrlFetchApp.fetch(apiURL, options);
Logger.log(response.getContentText());
}
I have figured out the answer. The Todoist API documentation is bit ambiguous, seeming written around POST requests, but to download (sync) a full list of tasks, a simple URL-encoded GET request, as constructed below, did the trick:
function getTodoistTasks(){
var apiURL = "https://todoist.com/API/v7/sync";
var queryString = "?token=" + getTodoistTokenRev() + "&sync_token=%27*%27&resource_types=[%22items%22]";
//Get params
var fetchParameters = {};
fetchParameters.method = 'get';
fetchParameters.contentType = 'x-www-form-urlencoded';
fetchParameters.muteHttpExceptions = true;
//make request and return
var response = UrlFetchApp.fetch(apiURL + queryString, fetchParameters);
var syncData = JSON.parse(response.getContentText());
return(syncData);
}
And if anyone is looking for an example of creating an item (a task in this case), as I was, here's the code for that (note you need to specify a date_string and due_date for it to appear in the web UI):
var API_URL = "https://todoist.com/API/v7/sync"
var BASE_QUERY = "?token=" + TOKEN
function addTask() {
// var taskName = SpreadsheetApp.getUi().prompt('What the task\'s name?')
var taskName = 'Test 1652'
var commands = encodeURI(JSON.stringify([{
"type": "item_add",
"temp_id": uuidv4(),
"uuid": uuidv4(),
"args": {
"content": taskName,
"date_string": "today",
"due_date_utc": "2017-12-2T18:00",
}
}]))
var queryString = BASE_QUERY + '&commands=' + commands
var options = {
method: 'post',
contentType: 'x-www-form-urlencoded',
muteHttpExceptions: true}
var response = UrlFetchApp.fetch(API_URL + queryString, options)
if (response.getResponseCode() !== 200) {
var content = response.getContentText()
throw new Error('URL fetch failed: ' + content)
}
var syncData = JSON.parse(response.getContentText())
return syncData
// Private Functions
// -----------------
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
} // addTask()

Google Script GET request issue

I'm trying to get a Google script (on a Google Sheet) to retrieve data from Float API. The endpoint and key are fine (tested and all works as expected on Postman) but it keeps returning 401.
Below is my code:
var API_KEY = "{ENTER YOUR KEY HERE}";
var ENDPOINT_PROJECTS = "https://api.float.com/api/v1/projects";
function getProjects() {
var headers = {
"Authorization" : "Bearer " + API_KEY,
};
var requestData = {
"method" : "GET",
"headers": headers,
"muteHttpExceptions": false
};
// Get the data
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS);
var responseCode = fetchResponse.getResponseCode();
if (responseCode == "200") {
var result = JSON.parse(fetchResponse.getContentText());
} else {
ui.alert("Error when attempting to fetch the list of spaces.");
}
}
Okay looked like I completely missed a small yet very important part...even though I created an object to hold the method and headers I was not passing this into the actual fetch!!! (This is what happens when you attempt to do a quick script at the end of the day)
So instead of this
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS);
we have this:
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS, requestData);

AngularJS $http sending data with Ajax URL

i have used this code before i use angularjs.
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "myUrl";
var fn = document.getElementById("username").value;
var ln = document.getElementById("password").value;
var vars = "username="+fn+"&password="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
if(return_data=="1"){
console.log("this is return data"+return_data);
}else{
ons.notification.alert({message: 'Login Failed!'});
}
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
}
Here with AngularJS to do same thing
$scope.ajaxLogin = function(){
var fn = document.getElementById("username").value;
var pw = document.getElementById("password").value;
$http({
url: "myURL",
method: "POST",
data: { username: fn, password: pw },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
if(status == 200) {
var return_data = data;
if(return_data == 0){
console.log("test "+data,status);
$scope.showAlertSucess();
}else{
$scope.showAlertError();
}
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.showAlertNetwork();
});
};
but AngularJS way its not giving expected output which is "1" it gives "0".
and i went through webconsole what i got is this part is different, i think it send data like JSON
data: { username: fn, password: pw },
but my other code its not like that
var vars = "username="+fn+"&password="+ln;
how to fix it to use with angularJS.
for more to understand here my PHP Code.
if ($result=mysqli_query($con,$sql))
{
$rowcount=mysqli_num_rows($result);
printf($rowcount);
mysqli_free_result($result);
}
If you use AngularJs to provide variable in PHP use this code
$array = json_decode(file_get_contents('php://input'));
In $array input your variables.

jsonp request receives 401 unauthorized

I'm using the select2 plugin to connect with LinkedIn's company search API. What I need is for it to work with jsonp so that I can avoid the "Access-Control-Allow-Origin" error I get with a regular json request [I've confirmed that the json request works when I disable the default security settings in Chrome.]. By "work" I mean I want the jsonp request url to authenticate me just as the json request url is, but I continue receiving a 401 unauthorized error.
I think my problem lies with the "callback" parameter in my url set by jsonp. For instance, the LinkedIn-authenticated company-search url created by json is:
http://api.linkedin.com/v1/company-search?keywords=mcdonalds&oauth_consumer_key=xxx&oauth_nonce=xxx&oauth_signature=xxx&oauth_signature_method=xxx&oauth_timestamp=xxx&oauth_token=xxx
With jsonp it is something like:
http://api.linkedin.com/v1/company-search?callback=jQuery19107866718948353082_1365690327081&keywords=mcdonalds&oauth_consumer_key=xxx&oauth_nonce=xxx&oauth_signature=xxx&oauth_signature_method=xxx&oauth_timestamp=xxx&oauth_token=xxx
The only apparent difference is the "callback=jQuery..." parameter. Here is my JavaScript:
function generateUrl(term) {
(function ($) {
var apiKey = 'xxx';
var apiSecret = 'xxx';
var memberToken = 'xxx';
var memberSecret = 'xxx';
var action = 'GET';
var path = 'http://api.linkedin.com/v1/company-search';
var nonce = '1234';
var timestamp = Math.floor((new Date()).getTime()/1000);
var version = '1.0';
var args = "keywords=" + term;
// var format = 'json';
if (args != '') { args += '&'; }
args += "&oauth_nonce=" + nonce + "&oauth_timestamp=" + timestamp + "&oauth_version=" + version;
OAuthSimple().reset();
this.results = (new OAuthSimple()).sign({
path:path,
action:action,
parameters:args,
signatures:{
'consumer_key':apiKey, 'shared_secret': apiSecret,
'access_token':memberToken,'access_secret':memberSecret}
}
);
}
(jQuery));
return results.signed_url.slice(results.signed_url.indexOf('?') + 1);
}
$("#linkedin").select2({
placeholder: "Search for a company.",
minimumInputLength: 1,
allowClear: true,
ajax: {
url: 'http://api.linkedin.com/v1/company-search',
dataType: 'jsonp',
data: function (term, page) {
return generateUrl(term);
},
results: function (data, page) {
return { results: data.companies.values };
}
},
formatResult: companyFormatResult,
formatSelection: companyFormatSelection,
dropdownCssClass: "bigdrop_3"
});
function companyFormatResult(company) {
return company.name;
}
function companyFormatSelection(company) {
return company.name;
}
Could it have something to do with the syntax of my url parameters? I was having problems when the "keywords" parameter wasn't immediately after "company-search?" in the normal json request, but moving the callback parameter in the jsonp request to the end of the url doesn't seem to help.
Thank you in advance.

Categories

Resources