how to get access token from bitly using password and username? - javascript

$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: { Authorization: "Basic " + btoa('myusername' + ":" + 'mypassword#123') },
success: function (result) {
console.log(result);
},
error: function () {
alert("Cannot get data");
}
});
I am trying to get access token from bitly api by providing username and password but it is showing invalid_client_authorization error. Does any one have idea on the same?
Bitly documentation : http://dev.bitly.com/authentication.html#resource_owner_credentials

You are concatenating your username with your authorization header.
Your authorization and content-type should go in the headers object.
There is no 'type' property on jquery ajax method, you probably meant 'method'.
Also, you can't send both dataType:'json' and set the content-type to 'application/x-www-form-urlencoded'
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
methdo: 'POST',
contentType: '',
dataType: 'json',
headers: {
'Authorization' : 'Basic ' + [INSERT YOUR HASH HERE],
'Content-Type' : 'application/x-www-form-urlencoded',
}
data: { $.serialize({
username: YOURUSERNAME,
password: YOURPASSWORD
})},
success: function (result) {
console.log(result);
},
error: function () {
alert("Cannot get data");
}
});
This should do it

Fixed #goncalomarques answer:
Removed top level "contentType" and "dataType"
Removed data object (otherwise username and password is sent as clear text, in addition to the hashed username and password in the header)
renamed "methdo" to "method"
Explicitly used btoa() to get Base 64 encoded hash (be aware, does not work in older IE versions)
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(YOURUSERNAME + ':' + YOURPASSWORD),
'Content-Type': 'application/x-www-form-urlencoded',
},
success: function(result) {
console.log("success");
console.log(result);
},
error: function(response) {
console.log("Cannot get data");
console.log(response);
}
});
Note:
I have this example working, but was unable to get it working with the built-in Stackoverflow editor ("Run snippet") due to cross origin exceptions.

Related

How to get oauth access_token with jQuery (localhost)?

I am trying to get access_token utilizing jQuery. Problem is, that I cannot get that token (server is running on localhost). Server works fine (I tried that with postman), but I cannot get it with jQuery.
Browser writes after clicking on the button.
The resource from “http://localhost:8080/oauth/token?callback=jQuery34105901959820360243_1562175129954&grant_type=password&client_id=my-client&client_secret=my-secret&username=test%40seznam.cz&password=Peter&_=1562175129955” was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff).
jQuery function to get access_token
function authenticateUser(email, password) {
var body = {
grant_type: 'password',
client_id: 'my-client',
client_secret: 'my-secret',
username: "test#seznam.cz",
password: "Peter"
};
$.ajax({
url: 'http://localhost:8080/oauth/token',
crossDomain: true,
type: 'POST',
dataType: 'jsonp',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
header: {"Access-Control-Allow-Origin": "*"},
data: body,
complete: function(result) {
alert(result);
},
success: function(result) {
alert(result + " OK!");
},
error: function(result) {
alert(result + " CHYBA");
},
});
return true;
}
If the javascript file is served by the same server that gives out the tokens then there's no need to use the full url in your jquery ajax code (and there's no need to indicate crossDomain=true). It also seems that your server is expecting json content type instead of url-encoded
use
url: '/oauth/token',
crossDomain: false,
...
contentType: 'application/json; charset=UTF-8',
To make the request
Edit
Trye this way:
$.post("/oauth/token",body,
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
Hope this helps

How to pass Authorization header in reactjs API call?

module.exports ={
_callAPI: function(url,method,data,target){
let token = "santhi" + ":" + "santhi";
let hash = btoa(token);
console.log(hash);
$.ajax({
url: BASEURL + url,
method: method,
data: data,
processData: true,
dataType: 'json',
headers: {
"Authorization" :"Basic " + hash,
"Content-Type" :"application/json"
},
success: (data,textStatus, jqXHR) => {
target('success', data);
},
error: (jqXhr,textStatus,error) => {
target('error',jqXhr,textStatus,error);
}
});
},
}
I am adding authorization as headers like thing. but i am not getting anything. Is there any other way to authorize base64 encoding.
Thanks in advance

Using Dropbox v2 API from Browser

I'm trying to upload data to dropbox via webbrowser (FF 42.0, PhantomJS 1.9.8) and dropbox v2 api. My function looks like this
function(path, data, callback) {
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
contentType: 'application/octet-stream',
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Content-Type","application/octet-stream");
},
data: data,
headers: {
"Authorization": "Bearer " + token,
"Dropbox-API-Arg": '{"path": "' + path + ',"mode": "add","autorename": true,"mute": false}',
"Content-Type": "application/octet-stream"
},
success: function (data) {
callback(data);
}
});
}
Even I set the Content-Type at all attributes I can think of to application/octet-stream I get the following error
Error in call to API function "files/upload": Bad HTTP "Content-Type" header: "application/octet-stream
; charset=UTF-8". Expecting one of "application/octet-stream", "text/plain; charset=dropbox-cors-hack"
Taking a look at the request in Firebug shows me that the Content-Type was really set to application/octet-stream; charset=UTF-8. When trying text/plain; charset=dropbox-cors-hack as Content-Type the sent request has text/plain; charset=UTF-8, and I get the same error message.
How can I make jquery and my browser to set the headers I need.
EDIT: Same behavior in Chrome
IE works as expected
Technically, Firefox is just adhering to the W3C XMLHttpRequest spec:
http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
Sending anything other than a Blob or ArrayBufferView can cause issues with browsers attempting to encode the data in UTF-8 (to follow the spec).
The right thing to do here is to avoid sending data as a String. Here are two examples of how to avoid this behavior:
// ... file selected from a file <input>
file = event.target.files[0];
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: file,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN,
"Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
}
})
Or, if you want to send up text, you can UTF-8 encode the text before uploading yourself. A modern way to do this is using TextEncoder:
var data = new TextEncoder("utf-8").encode("Test");
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: data,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN,
"Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
}
})
Try this...
private void upload(object sender, EventArgs e)
{
OAuthUtility.PutAsync
(
"https://content.dropboxapi.com/1/files_put/auto/",
new HttpParameterCollection
{
{"access_token",Properties.Settings.Default.AccessToken},
{ "path", Path.Combine(this.CurrentPath, Path.GetFileName(openFileDialog1.FileName)).Replace("\\", "/") },
{ "overwrite","false"},
{ "autorename","false"},
{openFileDialog1.OpenFile()}
},
callback : Upload_Result
);
}

Paypal Java script integration

Want to integrate Paypal with my mobile web application. I tried to get the access token using client id and secret id but unable to get the access token.
Below is the sample Ajax call with I am making to retrieve the access token.
function getAccessToken(){
$.ajax({
url:"https://api.sandbox.paypal.com/v1/oauth2/token/",
type:"POST",
data : {"grant_type":"client_credentials"},
beforeSend: function (request)
{
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Accept-Language", "en_US");
request.setRequestHeader("Authorization", "abc XXXXX:XXXXXXXXXXXXX");
},
success: function(data) {
alert(data);
},
error: function(e, messgae,type){
alert("Error" + e +" "+messgae+" type "+type);
}
});
I am unable to retrive the access token from the server.
Can anyone please tell me how can I integrate Paypal with my mobile web application using java script?
after a series of try and fail I found the correct AJAX call:
$.ajax({
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"Authorization": "Basic "+btoa("**<Client ID>:<Secret>**")
},
url: "https://api.sandbox.paypal.com/v1/oauth2/token",
type: "POST",
data: "grant_type=client_credentials",
complete: function(result) {
alert(JSON.stringify(result));
},
});
You need to replace Client ID:Secret with the one that you find on your Developer Dashboard, for example AxxhGDh:hudh-X-h8qi
Above example doesn't works, below works for me:
var parameter = {
"grant_type": "client_credentials",
"username": "<username>",
"password": "<password>"
}
$.ajax({
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"Authorization": "Basic <your auth key>"
},
url: "https://api.sandbox.paypal.com/v1/oauth2/token",
type: "POST",
data: parameter,
complete: function (result) {
alert(JSON.stringify(result));
},
})

jQuery JSONP ajax, authentication header not being set

I'm trying to make an ajax request to the google contacts API with the following setup:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
headers: {
'Authorization': 'Bearer ' + token
},
success: function(data, status) {
return console.log("The returned data", data);
}
});
But the Authentication header doesn't seem to get set. Any ideas?
I had the same problem recently. Try this:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
success: function(data, status) {
return console.log("The returned data", data);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + token); }
});
EDIT: Looks like it can't be done with JSONP. Modify HTTP Headers for a JSONP request
When authentication is needed in a cross domain request, you must use a proxy server of some sort.
Since using dataType: jsonp results in the HTTP request actually being made from the script that gets added to the DOM, the headers set in the $.ajax will not be used.
Is seems that most of the OAUTH2 REST resources accept the access_token parameter as part of the request url
http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#query-param
please, try the following code instead:
$.ajax({
dataType: 'jsonp',
url: url,
data: {
'access_token':token.access_token
},
jsonpCallback: 'thecallback',
success: function(data){
_cb(data);
},
error: function(d){
_cb(d);
}
});
Just do this (jquery 2.0, but should work in previous versions)
$.ajax({
url: "/test",
headers: {"Authorization": "Bearer " + $('#myToken').val()}
})
.done(function (data) {
console.log(data);
})
.fail(function (jqXHR, textStatus) {
alert("error: " + textStatus);
});

Categories