basic authentication not working javascript - javascript

I am having some trouble getting a few things working. I am trying to connect through basic authentication. I am using javascript in my HTML code. I get the following error message: " Failed to load http://**********/connections?********* : Response for preflight is invalid (redirect)" where I have redacted the API endpoint. The code I wrote is the following.
var Key = "something";
var Secret = "something else";
var url = 'http://**********';
$.ajax({
headers: {
'X-******-Key':Key,
'X-**********Secret':Secret,
'Content-Type':'application/x-www-form-urlencoded'
},
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(json) {
alert("Success", json);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(Key + ":" + Secret));
},
type: 'GET',
contentType: 'json',
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
hi
</html>
You can substitute the API end points and secret and Key to try the code for a common basic authentication API to try the code. I don't have access to the Server. I know it is still possible to make this work because someone else said they have this working. Can anyone help me with this?

Response for preflight is invalid (redirect)
Your server doesn't handle CORS properly.
Browsers won't let fetch data via ajax if the request is made to an external domain unless the server handles CORS properly and CORS headers are available in the responses.
Please read the article:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Related

Twitter API setting Authorization header in jQuery AJAX

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.

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...

$.post (to different domain) not working (node.js / express app on port 8081)

I receive the error POST https://thewebsite.com 400 (Bad Request) when using $.post that way:
$.post("https://website.com/blabla",
{
domain: "infoinfo.com",
room: "someInfo",
application: "someInfo",
ident: "someInfo",
},
function (data,status) {
alert("Data: " + data + "\nStatus: " + status);
});
I tried setting res.header('Access-Control-Allow-Origin', "*"); in my route but that didn't work.
Any ideas on how I could fix this?
Ps.: The server I am posting to is service website (xirsys.com), I am pretty sure they allow external domains already. I'll contact them during the day if I can't find a solution (I am using the jQuery post as they suggested :/
Try to add this to your AJAX call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Another reason maybe because of the same origin policy:
In computing, the same origin policy is an important security concept
for a number of browser-side programming languages, such as
JavaScript. The policy permits scripts running on pages originating
from the same site to access each other's methods and properties with
no specific restrictions, but prevents access to most methods and
properties across pages on different sites.
You can find out more informations about this issue from MDN docs or doing some research on Google about this topic.
You can try to use $.axax() like this:
$.ajax({
type: 'POST',
url: "https://website.com/blabla",
data: {
domain: "infoinfo.com",
room: "someInfo",
application: "someInfo",
ident: "someInfo"
},
dataType: "json",
contentType: "application/json",
success: function (e) {
alert("Data: " + data + "\nStatus: " + status);
}
});
This is due to the Same-origin policy. All the browsers as a security measure would not allow any cross domain requests.
http://en.wikipedia.org/wiki/Same-origin_policy
Like in your case you are posting to thewebsite.com domain from a different domain. A work around is to use the jsonp (the server should support json padding) from the jquery.
Check these sites for more info
http://www.jquery4u.com/json/jsonp-examples/
http://en.wikipedia.org/wiki/JSONP
http://stackoverflow.com/questions/6871021/how-to-enable-cross-domain-request-on-the-server
SAMPLE REQUEST:
$.ajax({
url: "http://yoururl",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
alert("success");
},
error: function (xhr, status) {
alert("error");
}
});
SAMPLE RESPONSE IN PYTHON:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
The link I was posting to was actually not good. The service I am using updated the link in their API to reflect the right one.

Cross domain issue with jsonp and HTTPS

I have a web page build through HTML, Javascript and ajax. I need to request resource from another domain. The request is through HTTPS. My website is on HTTP. To address cross domain issue I used Jsonp as the data type. Here is my request method.
$.ajax({
url: 'http://xxx.xxx.xxx.xxx:yyyy/service/sv1',
type: "GET",
contentType: "application/json",
async: false,
crossDomain: true,
data: { 'parm': parmval },
dataType: 'jsonp',
success: function (json) {
alert(json.info);
},
error: function(xhr, statusText, err) {
alert("Error:" + xhr.status);
}
});
Still I am not getting any response! Chrome says Failed type and status pending.
Is there anything wrong in the above code? Did i addressed cross domain issue?

login to jenkins using ajax/javascript

I want to run a Jenkis job that requires login from a web page (outside of jenkins) using ajax
currenly i have to have another browser tab with jenkins open (and authenticated) in order for the job to run from my web page
iv'e tried different approaches to sending the authentication info with ajax
this is what i currently have:
$.ajax({
type: "POST",
url: "http://myjenkins/job/job_name/buildWithParameters",
dataType: 'jsonp',
data: $("#myForm").serialize(),
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "username:password");
},
success: function(data) {
},
complete: function(xhr, statusText){
}
});
(there's some more HTML code that receives parameters from a form)
if i have an open tab with jenkins authenticated this runs fine, but if i don't i get a "430 forbidden" responce from jenkins.
the "xhr.setRequestHeader("Authorization", "username:password");" is just my latest attempt...
any input is welcome!
This worked for me, thanks a lot, just to expand, it worked because As per RFC 1945, the Authorization header value should contain the username:password as encoded (base64) string, which would result in something like the following header:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
example:
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:token"));
}
beforeSend: function (xhr) {
xhr.withCredentials = true;
data: $("[name='parameters']").serialize()
xhr.setRequestHeader("Authorization", "Basic " + btoa("test:d8db6ae61f03219c52042638488e9744"));
},
works for me

Categories