in Ajax, how to write "headers" for multiple condition? - javascript

as a beginner, I have some problems in using Ajax (with Discogs API) .. to get a discogs request token, discogs is saying
Include the following headers with your request:
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback"
User-Agent: some_user_agent
https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow
but, how to write this header?
below is my trying code, but I know this is not proper.
$.ajax({
type: "GET",
url: "https://api.discogs.com/oauth/request_token",
dataType: 'jsonp',
headers: {
ContentType: "application/x-www-form-urlencoded",
Authorization: OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback",
UserAgent: some_user_agent,
}
success: function (data) {
console.log(data);
document.getElementById("content").innerHTML += "<br>" + `${data}`;
},
error: function (error) {
console.log(error);
}
});

You said:
dataType: 'jsonp',
It isn't possible to specify headers for JSONP requests.
The API can't be using JSONP. Set the dataType to the format they are using.
The documentation says:
When you create a new application, you’ll be granted a Consumer Key and Consumer Secret, which you can plug into your application and start making authenticated requests. It’s important that you don’t disclose the Consumer Secret to anyone.
Putting those in your client-side code will disclose them to all your visitors.
The request to that end point should be made from server-side code.

Related

How to use transactional Cypher HTTP endpoint and new REST API Authentication and Authorization in Neo4j 2.2.x with JQuery

I'm looking for a code example creating a REST POST request with JQuery on Neo4j 2.2.x Transactional Cypher HTTP endpoint with new REST API Authentication and Authorization parameters.
Before Neo4j 2.2 version I used the Legacy Cypher HTTP endpoint (which is deprecated) to execute Cypher queries with the following code:
$.post("http://localhost:7474/db/data/transaction/commit",
{
"query": query,
"params": {}
}, "json")...
But I would like to move to 2.2 and use the transactional endpoint with user authentication parameters.
I can't find the right headers and parameters combination to use to create such a request. That's why I'm looking for a code example.
Best would be an example using a cross domain request but an example on same domain would be helpful too.
For authentication you need to supply an additional HTTP header to your request:
Authorization: Basic realm="Neo4j" <base64>
where <base64> is the base64 encoded string of username:password.
Not being a jquery ninja, but I guess the most simple way is to set the authorization header using ajax defaults:
$.ajaxSetup({
headers: { "Authorization": 'Basic realm="Neo4j' <base64>'}
});
When this default has been applied your $.post above should work.
The issue has been fixed in 2.2.0-RC01 and I can use transactional Cypher HTTP endpoint with authentication using the following example code:
$.ajaxSetup({
headers: {
// Add authorization header in all ajax requests
// bmVvNGo6cGFzc3dvcmQ= is "password" base64 encoded
"Authorization": "Basic bmVvNGo6cGFzc3dvcmQ="
}
});
$.ajax({
type: "POST",
url: "http://localhost:7474/db/data/transaction/commit ",
dataType: "json",
contentType: "application/json;charset=UTF-8",
data: JSON.stringify({"statements": [{"statement": "MATCH (n) RETURN n LIMIT 10"}]}),
success: function (data, textStatus, jqXHR) {
// use result data...
},
error: function (jqXHR, textStatus, errorThrown) {
// handle errors
}
});
Authorization means that the browser will send a preflight OPTIONS request which does not embed authorization headers.
This is most known as CORS.
Currently the Neo4j server do not reply to the OPTIONS request with the appropriate Access-Control-Allow-Headers.
This feature has been implemented in the source code and will be shipped with the GA release which I hope will come out this week.

Bigcommerce legacy API validation javascript example

I need to validate Bigcommerce legacy API credentials using AJAX (more precisely, using $http in AngularJS)
Every time I post a request to a store api, I always get the response:
[{"status":401,"message":"No credentials were supplied in the request."}]
I've tried every combination of parameters and headers that I can think of, and still I get the same error message. I could not find a single example of javascript code to validate the old Bigcommerce API credentials (legacy API).
Please help!
Bigcommerce clients provide the following data:
username, api_path, api_token
Here is my code:
var encoded_access_token = window.btoa(unescape(encodeURIComponent(
$scope.merchant.username + ':' + $scope.merchant.api_token
)));
$scope.merchant.api_path = 'https://store-ji3ql.mybigcommerce.com/api/v2/time';
$http({
method: 'GET',
url: $scope.merchant.api_path,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, application/xml, text/plain',
'Authorization': 'Basic ' + encoded_access_token
},
isArray: false
}).success(function(returnData) {
console.log('success!');
console.log(returnData);
}).error(function(returnData) {
console.log('error!');
console.log(returnData);
});
As I know, you could not validate Bigcommerce legacy API credentials with JS but a backend language such PHP, Ruby, ...
You could employ BC's APIs on you own server with PHP then expose it for JS code to call from.
(I have not implemented on my own, but that's what I heard from a bigcommerce developer)
Please visit this for more information: https://developer.bigcommerce.com/api/clients

Possible to get Asana tasks through JSON-P and Asana Connect?

Is it possible to connect to ASANA without a backend?
We have a secure folder on a webserver where we'd like to retrieve a task list of a project using only Javascript. Is that possible?
I saw some news from Asana that they support JSON-P through Asana Connect, but it's a bit unclear on how you could set this up from the documentation. Is there any examples available that I haven't found? Or have anyone succesfully set this up earlier?
The preferred way to do this is using CORS (added November 2013) - see this gist for an example of how you can use it. If you're unfamiliar with CORS, it stands for Cross-Origin Resource Sharing, and allows you to make cross-domain requests, given that the headers of the client and server match appropriately.
Incase anyone is already using Jquery (like I am) you can use the following code to do the same as the example from #agnoster.
$.ajax({
url : 'https://app.asana.com/api/1.0/users/me',
dataType : 'json',
type: 'GET',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(api_key + ":"));
}
}).done(function(response) {
console.log(response.data);
});
And if you need to POST/PUT you can use jQuery like this:
$.ajax({
url : https://app.asana.com/api/1.0/tasks/taskid',
dataType : 'json',
type: 'PUT',
data: { "completed": true },
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(api_key + ":"));
}
});
PS! you'll not be able to get this working for IE9 as it does not support sending headers (so the xhr.setRequestHeader() won't work)

Using CORS for Cross-Domain Ajax Requests. Test on httpbin.org doesn't work

I know that the issue already was discussed a lot. I went through the whole bunch of other SO's questions, but still has no solution.
My test case is very simple.
Requirements
I need to get authorised on httpbin.org site from my local server (localhost:63342). Basically I use http://httpbin.org/basic-auth/user/passwd to test HTTP Basic Auth.
I test Basic HTTP Authentication via jQuery.ajax function using GET request.
I need to get this done using exactly REST because actually my real goal is to get authorised via REST API request on teamcity's server which uses GET requests.
What I have done so far
Actually I tried enourmous things (worked with headers(Access-Control-Allow-Credentials, Access-Control-Allow-Origin), tried to use beforeSend function, dealt with jsonP, etc). No luck.
<html>
<head>
<script src="./jquery-1.11.0.js"></script>
</head>
<body>
<div id="target">
Click here
</div>
<script>
$("#target").click(function() {
var username = 'user';
var password = 'passwd';
$.ajax({
type: "GET",
beforeSend: function (xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
// I know, this one is redundant
xhrFields: { withCredentials: true },
crossDomain: true,
headers: { 'Access-Control-Allow-Credentials': true },
headers: { 'Access-Control-Allow-Origin': '*' },
// this one is redundant too
headers: { 'Authorization': "Basic " + btoa(username + ":" + password) },
//contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
url: "http://httpbin.org/basic-auth/user/passwd",
success: function(data, textStatus, jqXHR){
alert('success');
},
error: function(jqXHR, textStatus, errorThrown ) {
alert('failure');
},
// I don't know if I have to write it directly or not
username: 'user',
password: 'passwd'
});
});
</script>
</body>
</html>
Results I get
During all my tests I got different results. The code above causes httpbin to show auth popup window to type credentials (it's weird because I send user/pass pair in headers). Another results I've got were: UNAUTHORIZED status (which is quite understandable), "error" error message (which is meaninless), etc...
Experts of jQuery and cross-domain requesting, please help to figure out what should be done here.
P.S. I know this is highly related to CORS issue, but I tried to set Access-Control-Allow-Origin in different ways without any success.
Update:
Actually my initial goal is to be able to invoke CI job from JS code (TeamCity job via REST API using Basic HTTP AUthentication).
So, for TeamCity I believe there is a bug there (in REST API Plugin) - anyone who is interested in, please track the issue TeamCity's REST API Plugin doesn't allow to authenticate using Basic HTTP Authentication
Regarding httpbin.org - test is invalid at all.
Thanks a lot!

Get OAuth request token through JSONP

I am trying to make a pure JavaScript Twitter application. I'm not concerned about the security involving the tokens since this is for internal use.
Currently, my code looks like this:
$.ajax({
url: 'https://api.twitter.com/oauth/request_token',
type: 'post',
data: {
oauth_callback: callbackurl
},
dataType: "jsonp",
headers: {
"oauth_nonce": nonce1,
"oauth_callback": callbackurl,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": Math.round(new Date().getTime()/1000),
"oauth_consumer_key": "IQKbtAYlXLripLGPWd0HUA",
"oauth_signature": "Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", //generate
"oauth_version": "1.0"
},
success: function(data)
{
console.info(data);
}
});
This code is rather incomplete, but the goal is to get what Twitter is returning (the request tokens). Obviously this code is not going to work because it violates cross origin policy. I have heard that this is possible with pure JavaScript, though. I need to send Twitter headers (at least, I think they have to be headers) then retrieve what they return.
Is there a workaround for this?

Categories

Resources