Getting 400 response on GET request from AJAX - ajax

I'm trying to access my API using AJAX with the simple following code:
$.ajax({
type: "GET",
url: "http://SERVER_IP/API-test/public/login/username/userpass",
crossDomain: 'true',
dataType: 'jsonp',
contentType: "application/json",
success: function(whatever){
alert('HTTP request is a success');
console.log(whatever);
},
error: function(errorText){
console.log("Error Test: ",errorText);
}
});
and in response I get 400 (Bad request) from the server. This code generates following request:
http://SERVER_IP/API-test/public/login/username/userpass?callback=jQuery1112009842987591400743_1429090394748&_=1429090394749
I guess that the problem is in the part this part:
?callback=jQuery1112009842987591400743_1429090394748&_=1429090394749
that is added to my request.
How could I avoid this? Or could be the root of the problem somewhere else?

Whether the Query Parameters result in a HTTP Code 400 depends on you server implementation.
Bot parameters are added by jQuery.ajax to avoid issues with caching.
The _ parameter includes the current timestamp to avoid caching.
The callback parameter is added because you are querying a "remote" server (= crossdomain) with jsonp "technique", which means the url is not same as the url the javascript/html/etc files have been loaded from.
Beside that you are querying a login endpoint (at least it is named like that) and do not send any verification data like username or password. When performing a GET request, these information needs to be included in the query part. Maybe the server returns "Bad Request", because the credentials are missing?

Related

Securing web api using random session number

I am making a web API/Rest API in MVC where each API takes one parameter called user_session
So when a user logs in, I generate a 10 digit session and pass it back to user which needs to be given as input for any subsequent API calls.
Here's what my typical code looks like:
$.ajax({
url: '#Url.Action("GetUserDetail", "myapi")',
type: "GET",
data: { UserID: '#user.user_id', SessionID: '#user_session' },
dataType: "json",
success: function (response) {
}
})
My question is, is this the right approach or is there a better way of doing it? Is it secure?
You can very well use the HTTP Cookies for remembering the session instead of manually passing it as a param for every request.
I’ll give very short explanation on this topic.
Server sets a cookie when a user logs-in.
This cookie will be sent to all the api calls as it is defined as a HTTP cookie.
Server can validate or know about the session using this cookie value in header of the request.

How do you put a User Name/Password in JSON format to be used to set XHR reques header

In Below example, if i use username and password, then anyone can see it in page source. Is there any solution to hide the username and password or can we put credentials in json or xml file and access it to set it in header, if yes please let us know the solution.
$.ajax({ type: "POST",
contentType: false,
data: formData,
url: "external domain URL",
crossDomain: true,
cache: false,
processData: false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username" + ":" + "Password"));
xhr.withCredentials = true;
},
You can encode username and password into a text and use that text, but this is dangerous and unfeasible, because that way if someone manages to decode it for some reason, then it will be a huge security leak. And if the server accepts an encoded text, that would also be a security leak, so you should avoid this kind of approach, unless you use some temporary tokens, but that would only reduce, but not eliminate the risk.
Instead, it would be much better if you had a page, which would work as follows:
when the data is needed, a request is sent to the server to gather the username and password
the server will respond with an encoded variation of these data
the client-side would decode this
the client-side will send the request
Also, you could use your server as a proxy, that is, send all the requests to your own server instead of the target server and the server on its turn will forward the request to the target server and the response to the client-side. This would be even better.

Ajax result is getting encoded

I have a page where onload I issue several POST requests simultaneously in order to load widgets on the page. The request looks something like this:
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: JSON.stringify({}),
success: function(htmlResult) {
$div.html(htmlResult);
}
})
Most of the time everything loads fine. However, some of the time one of the widgets will get loaded with a replacement character. It's not one specific widget that this happens to, but it could be any one of them at random.
When I inspect the bad HTTP response, I notice that the Vary header has a value of Accept-Encoding and the body is encoded. All the other responses have a value of * for that header, and the body is text/html. I'm not explicitly setting the Vary header value anywhere.
I can't figure out what's causing this random behavior. Any ideas?
FYI, I'm posting to an ASP.NET MVC action, and returning a partial view.
have you tried dataType:'json' instead of 'html'?

Why is my json request erroring instead of succeeding?

Here is my debugging method that goes to the error block instead of the success block.
function removerelationship(reference_related_id_var) {
if ($('##relationships').attr('id') != undefined) {
$.ajaxSetup({cache:false});
$.ajax({
url: 'index.cfm?action=reference.confirmjson',
dataType: 'json',
data: {reference_id:reference_id_var, reference_related_id:reference_related_id_var},
success: function(){alert("I PASSED");},
error: function(){alert("I FAILED");}
});
But this is my response from calling reference.confirmjson:
{"MESSAGE":"Are You Sure You Want To Remove The Relationship Between References 744094 and 1200?","CONFIRMED":true}
Is there some reason this would still take me to the error block?
Thanks.
Make sure you have debug output turned off for the AJAX request . I explain it a bit better at http://orangexception.com/post/7308110027/remove-debug-output-from-ajax-requests-in-coldfusion
The error case would be called if any status other than a 200 is being returned. Take a peek at the response in Firebug or a similar tool. If CF is also throwing an error further down the request, it would return a 500. This can help you determine if you need to check the CF application log for an error.
Edit: Also, check the raw response. Firebug does an awesome job at dropping the trailing CF error and just showing the properly formatted JSON, which could be confusing if an error was thrown.

jQuery AJAX JSON dataType Conversion

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.
Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}
Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):
$.ajax({
type: 'GET',
url: 'http://username:api-key#www.kanbanpad.com/api/v1/projects.json',
contentType: 'application/json',
dataType: 'jsonp',
converters: {
'jsonp': jQuery.parseJSON,
},
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log(textStatus+': '+errorThrown);
}
});
If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.
It may also be worth noting that if you copy/paste the API URL into a browser address bar and hit go, it gives the proper JSON response with the proper response header ("application/json")
So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.
It works just as well, it just requires an extra step is all.
Just for anyone that was looking for a solution.
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering
function to sanitize the response. You should return the sanitized data. The function
accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
I would change the content type in the dataFilter interceptor to json. Bear in mind this affects all ajax calls, so use info from data to decide which ones you want to convert.
Verify that your server is sending a jsonp response. This means the json should be enclosed with a string of your callback.
The callback name is passed in the parameters, and if you're not setting it explicitly, looks something like: jQuery15102810791094068532_1300988427891 (As per http://www.json-p.org/)
On your server, you need to format the response:
jQuery15102810791094068532_1300988427891({...json response ...});
Where you use the callback defined in your GET parameter 'callback'.
You might try setting the type to "json" and see if it works. I've had a number of parsererror's with the jquery's jsonp - you might try http://code.google.com/p/jquery-jsonp until it's a bit smoother.
Try changing your content-type to this
contentType: "application/json; charset=utf-8",

Resources