Javascript HTTP Auth to another site with greasemonkey script - javascript

On site1.domain.com I am running a greasemonkey script that takes in user credentials to authenticate to site2.domain.com and pull the entire page and parse out a server generated token that is needed to complete the rest of the script running on site1.domain.com and then make another URL GET to site2.domain.com.
xmlhttp.open("GET", url, false, username, password );
is the call I'm attempting but I'm receiving the error "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied". I looked around and I understand that there are complications with this type of functionality but I haven't figured out what I need to do in this situation.
EDIT: Tried this using verisons of the code below but receiving Cross-domain error for any datatype other than jsonp but with jsonp I recieve "htmlString is undefined". I also tried defining the return value as a String and in that case I received "6" (without any manipulation).
var htmlString = getPage(url,username, password);
var index = htmlString.indexOf("Token");
//some other code that parses out just the token, shown as "finalString" in the end
$("#logMessage").text (finalString);
function getPage(url, username, password) {
return $.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
async: false,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', btoa(username + ":" + password));
}
}).responseText;
}

Related

AJAX - Get cross-origin XML data with username and password

I'm trying to do a cross-origin request to a server to retrieve some XML data via AJAX. The XML data is password protected and I have to enter credentials in order to access it. I'm trying to autopopulate these fields so that obviously me nor the user has to write them in every time they want to retrieve some data but can't seem to succcessfully pass these through with my request as it still prompts me for a username and password. Here's my code:
$.ajax({
type: "POST",
url: "https://example.com/api",
data:"?&mydata=1&moredata=2",
dataType: "jsonp xml",
crossDomain:true,
beforeSend: function(xhr){
xhr.withCredentials = true;
},
username:"user",
password:"pass",
success: function(xml){
console.log(xml)
}
});
I'm pretty suer i've added all the necessary configuration. Can anyone spot if i've missed something or if there's an alternative way to do this?
thanks

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

PhoneGap - Sending JSON encoding data error

I am using Phonegap to connect to a server to authenticate a user. The server expects the data to be Json encoded, and I will get the response back from the server.
var serviceURL = "http://appdev/PEPS-CS-Services/";
The serviceURL (APPDEV) is hosted on our network within the office.
var loginData = {
'strUniqueID' : '123',
'UserName' : 'User123',
'Password' : 'Password123'
};
I have checked the login credentials and they are fine. When I try the following:
$.ajax({
type: "POST",
url: serviceURL + "services/AuthenticationServices/authenticateUser",
data: loginData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
I get the Access-Control-Allow-Origin error in my console.
XMLHttpRequest cannot load http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
I had a look around, and I was suggested to use Jsonp as the dataType in the ajax request, which does give me back the response I was looking for. However, it isn't alerted out as it should be, the console shows the url with the parameters used in the loginData variable, as below
Resource interpreted as Script but transferred with MIME type application/xml:
http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser?callback=jQuery164017807046906091273_1396515434941&strUniqueID=123&UserName=Mark&Password=Password1&_=1396515434963"
When I open the link in a browser i get the correct response, as below
<ns:authenticateUserResponse xmlns:ns="http://services">
<ns:return>SESSION ID HERE</ns:return>
</ns:authenticateUserResponse>
However, I also get the Uncaught SyntaxError: Unexpected token < error below it.
I have tried to change to data: loginData to data: {'data':$.toJSON(loginData)}, but still the same error.
My questions are the following:
Am I sending the data over correctly? Why does the jQuery164017807046906091273_1396515434941 get added to the URL before the parameters?
And why am I getting the Uncaught SyntaxError too?
Is this because the server is sending back the incorrect format of the data? It is currently sending back XML
Any help would be greatly appreciated, thanks
This is a familiar cross context issue, you are not allowed to request resource from another domain with simple ajax call and expect a result.
Instead, use a jsonp call and regiter a callback function to call when return result:
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
/* show json parsed data */
alert(data);
};
$.ajax({
url: serviceURL + "services/AuthenticationServices/authenticateUser",
dataType: 'jsonp', //use jsonp data type in order to perform cross domain ajax
crossDomain: true,
data: loginData,
success: success,
error: function(errMsg) {
alert(errMsg);
}
});

Connecting to Rest Server with jquery and ajax

i am trying to make a call to a rest server using jquery/ajax
The rest Server is built in Codeigniter
The ajax function is as follows:
var req = $.ajax({
type: 'GET',
url: "http://localhost/projects/comp6300Server/index.php/resources/token//username/" + email + "/password/" + pword + "/institution/" + inst,
contentType: "application/json; charset=utf-8",
dataType: "json"
})
The request that is generated is as follows:
http://localhost/projects/comp6300Server/index.php/resources/token//username/etambie#yahoo.com/password/qwerty/institution/BCC
The status returned is '400 Bad Request'
I think the problem may be with the email that is passed in "etambie#yahoo.com". Is there a way for the ajax automatically convert the '#' to '%40', or would i have to convert all special characters in my strings manually?
Two things to check out:
The "_" parameter is probably added to that each request is unique. If this isn't done, then the browser may attempt to get the result of calling the URL from it's cache, which is probably not what you want.
On the bad request ... are you sure you want two slashes after the word 'token' in your url?

jQuery AJAX Cross Domain with BASIC Authentication

I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.
What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.
<script type="text/javascript">
$(document).ready(function() {
var tok = 'username' + ':' + 'password123';
hash = btoa(tok);
authInfo = "Basic " + hash;
$.ajax({
url: "http://username.beanstalkapp.com/api/changesets.json",
beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
type: "GET",
async: false,
crossDomain: true,
dataType: "json",
success: function(html){
console.log(html);
},
error: function(html){
console.log('error');
}
});
});
</script>
If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!
You will need to make proxy for cross-domain ajax requests.
Usual scenario looks like this:
Client send ajax request to server
Your server forwards request to external/remote server
Waiting on response from remote server
Parse and process response from remote server
Send response back to client
If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.
you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.
Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.

Categories