Twitter API setting Authorization header in jQuery AJAX - javascript

I have a problem. I have the Authorization header generated by OAuth Tool in Twitter (I hid value of keys)
Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxxxx", oauth_nonce="xxxxxxxxxxxxxxxx", oauth_signature="xxxxxxxxxxxxxxx", oauth_signature_method="HMAC-SHA1", oauth_timestamp="xxxxxxxxx", oauth_version="1.0"
And I have a AJAX code:
$.ajax({
url: 'https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames&since_id=24012619984051000&max_id=250126199840518145&result_type=mixed&count=4',
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="xxxxxxxxxxxxxxx", oauth_nonce="xxxxxxxxxxxxxxx", oauth_signature="xxxxxxxxxxxxxxx", oauth_signature_method="HMAC-SHA1", oauth_timestamp="xxxxxxxxx", oauth_version="1.0"');
},
dataType: "jsonp",
success: function(data) {
console.log("Success: " + data);
}
},
error: function(data) {
console.log("Error " + data);
}
});
But this code returned error
Object {readyState: 4, status: 404, statusText: "error"}
Here is part of documentation Twitter REST API which I use:
https://dev.twitter.com/rest/reference/get/search/tweets
What is wrong? Any ideas?

Twitter does not support generating the authentication header from a webpage. You must go through the "handshake" using their site to authenticate and redirecting back to your webpage.
If you want to avoid this and keep your oauth keys locally, you will need to build a server which can authenticate using stored keys. Then your webpage will make Twitter requests via your server.

Related

Bypassing XSRF token check

I am attempting to utilize jQuery AJAX to POST dynamic data into JIRA. The idea is to POST to the JIRA REST API via "rest/api/2/issue/".
I believe I have all of my jQuery laid out properly. The issue I'm having trouble getting past is the "XSRF token check" upon execution. Every time I attempt to run my code, it returns "XSRF token check failed" from the server.
I have read about the "X-Atlassian-Token" header. I have that as an allowed header on my jira server config. i.e...
'Header always set Access-Control-Allow-Headers "X-Atlassian-Token, Authorization, Content-Type"'
I have also set the header on my AJAX request. "X-Atlassian-Token": "no-check"
Can someone assist me in getting this to work properly?
JIRA version tested with is 6.4.12.
My current AJAX code is below for review.
$.ajax({
url: "https://my-jira-host.com/rest/api/2/issue/",
type: "POST",
async: false,
headers: {
"X-Atlassian-Token": "nocheck",
"Content-Type": "application/json",
"Authorization": "Basic " + btoa("<username>:<password>")
},
crossDomain: true,
dataType: "json",
data: JSON.stringify({"fields":{"project":{"key":"CLS"},"priority":{"name":"Minor"},"customfield_17125":{"value":"<Department>"},"customfield_17127":"<HOSTNAME>","customfield_17126":{"value":"<Object>"},"issuetype":{"name":"<issue-type>"},"customfield_17128":"dsfgfdsg","summary":"Department | HOSTNAME | Object","description":"sdfgfdg"}}),
success: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("POST was a success!");
console.log("HTTP Error Message: " + XMLHttpRequest.responseText);
console.log("HTTP Status: " + XMLHttpRequest.status);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("POST was a failure!");
console.log("HTTP Error Message: " + XMLHttpRequest.responseText);
console.log("HTTP Status: " + XMLHttpRequest.status);
}
});
I should also mention that this code is being sent from client website I created internally. Both client front-end and JIRA host are on the same internal network.
XSRF (Cross Site Request Forgery) is a security feature used by Jira to prevent users from being tricked into submitting malicious data.
If you are using Firefox or Chrome, you may need to set the User-Agent with a dummy value like this:
headers: {
"X-Atlassian-Token": "nocheck",
"Content-Type": "application/json",
"Authorization": "Basic " + btoa("<username>:<password>"),
"User-Agent": "xx"
},

AJAX: JWT auth for video load via src

I am requesting a video from an API that requires JWT web tokens:
// when the ajax call is done (the tolken is recieved )
getAccessToken.done(function(data) {
var d = JSON.stringify({'fpath': fpath})
// get the download url
var downloadurl = $.ajax({
type: "POST",
url: "https://gcp.inbcu.com/download",
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "JWT " + data.access_token);
},
contentType: 'application/json',
data: d,
success: function(response){
$('#video-source').attr('src', response.url)
$('#myvideo').load()
},
error:function(jqXHR, textStatus, errorThrown) {
console.log("request for download url failed: ", textStatus, errorThrown, jqXHR);
},
dataType: 'json'
});
This ajax call itself is successful (200) and returns the proper values. Mainly it returns a url to set the source of the video.
Problem is, the video src attempts to access the url and doesn't have permission (no jwt token/ authorization). How am I supposed to load the video with the proper permission when loading the src of a video? Is this possible?
As the answer to a similar question explains, this isn't possible. Either you need to do it as an AJAX request, which you previously did, but which was slow, or, you need to add additional methods for the server to accept authentication.
Regarding these auth options, you could add a session cookie that the server can check, or append the token to the video url, like response.url + '?token=' + token.
A service worker would be capitabel of adding the auth token. But that only solves the problem for FF & Blink

(Spotify Web API) Create New Playlist - POST request returning 'Error 403 (Forbidden)'

Here is the link to the Web API notes on how to create a new playlist. https://developer.spotify.com/web-api/create-playlist/
As far as I understand, the POST requests the url https://api.spotify.com/v1/users/{user_id}/playlists. This is requested while passing the access token and data. The content type of the data being 'application/json'.
For some reason this is failing and returning a Error 403 (Forbidden) in the console.
Anything I'm missing?
//(playlistName, userId, accessToken) are passed to this.
var urlString = 'https://api.spotify.com/v1/users/' + userId + '/playlists';
var jsonData = {
"name": playlistName,
"public": false
};
$.ajax({
type: 'POST',
url: urlString,
data: jsonData,
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
},
contentType: 'application/json',
success: function(result) {
console.log('Woo! :)');
},
error: function() {
console.log('Error! :(');
}
})
Having tried your example, I get a 401 unauthorized when filling in bogus data. So you are authorized, but the API really does not grant you the rights (403 forbidden).
Please have a look at the authorization guide. I am pretty sure, your error is there. Especially have a look at scope. You might simply not grant enough power in the login. And therefore ending up with only public access, which does not include adding playlists.
I cite form the API docs:
To be able to create private playlists, the user must have granted the
playlist-modify-private scope.
https://developer.spotify.com/web-api/authorization-guide/

Jquery not handle HTTP errors when the request gets failed

My problem is "simple". I'm developing a hybrid Android application that makes HTTP requests via Jquery Ajax.
The problem is that when my requests gets failed(Server returns 401/403 ...etc), Jquery fires only HTTP 404 error that is not correct.
I'm making HTTP post requests like that:
var request = $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: obj,
cache: false,
contentType : 'application/json',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
},
success: function(data){
// Success
},
error: function(request, status, errorThrown){
console.log("call Login ajax failed with error, status:" + status + " errorThrown:" + errorThrown);
console.log("call Login ajax failed with errorCode : " + request.status);
}
The strange thing is that when i run my project as DynamicWeb project in my browser at my PC and in the url use my ip address the jquery fires the correct error events, but when i use "localhost" in the url, the jquery act as in the android devices, fires only 404 event.
I tried to change jquery libary to a newest version 2.1.1 but this doesn't help.
PS. I'm using jquery 2.0.2...
You'll need to set the header of the response to Content-type: application/json.
Before you echo the json. Or you could set the type of the ajax call to text, html.
Also it is recommended to chain your callback functions with jquery like so
$.ajax({
url: url,
headers: { "Accept-Encoding" : "gzip" }, // Use the response seen in sniffer
type: 'POST',
dataType: 'json',//be sure you are receiving a valid json response or you'll get an error
})
.done(function(response) {
console.log("success");
console.log(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
The problem for me was that server doesn't allow Cross-domain requests. So i must set "Access-Control-Allow-Origin:", "*" header in responses from my server and everything will be ok...

Salesforce OAuth with REST API using Javascript

I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.
Step 1) I request access token using username and password via the below code snippet
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username#location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
My request, however, is failing with the following message:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
I have seen some sources (here here here) mention that CORS is not supported in salesforce, and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.
In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to login users and access their salesforce data from my connected app?
All and any help is appreciated!
You will need to handle the OAUTH part on your own server. This isn't just due to lack of CORS, there is also no way to securely OAUTH purely on the client-side. The server could really be anything but here is an example server written in Java using Play Framework which has a JavaScript / AngularJS client as well: http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
You can not make this request from JavaScript. You'll need to make a server side request. There are many implementations of this flow in PHP, C#, Java, etc.
I'm posting my ajax code here that has worked for me and this CORS error in console doesn't matter. If you see in network you will get the access token.
see the ajax code below.
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
I hope this will work for you perfectly.
I think you need to add the origin URL/IP in CORS setting as well in salesforce if you are making a request from Javascript app so it can get access to salesforce data.

Categories