Ajax crossdomain request with jquery and BASIC-authentication? - javascript

I really appreciated if somebody could tell me what is wrong in that authentication? I take the authentication off from the server to test without it, but javascript is broken.
$('#btnSignIn').click(function() {
var username = $("#username").val();
var password = $("#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var final = "Basic " + $.base64.encode(tok);
console.log("FINAL---->" +final);
alert("FINAL---->" +final);
return final;
}
$.ajax({
type: "GET",
contentType: "application/json",
url: "http://localhost:8080/SesameService/webresources/users/secured/login",
crossDomain: true,
dataType: "text",
async: false,
data: {},
beforeSend: function (xhr){
xhr.setRequestHeader('authorization', make_base_auth(username, password));
},
success: function() {
alert('Thanks for your signin in! ');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(' Error in signIn-process!! ' +textStatus);
}
});
});
ERROR: If I take the
beforeSend: function (xhr){
xhr.setRequestHeader('authorization', make_base_auth(username, password));
-part off from the function, I can get into REST-service. I haven't got authentication on at the moment. Could this be the reason or shoud I have the authentication on in the server when using that header?
contentType: "application/json",
#GET
#Path("/secured/login")
#Produces({"text/plain"})
public String login() {
return "Is it working or not?";
}
When using beforeSend-part in JS, I got an error:
[Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://localhost:8383/Sesame/assets/js/jquery.min.js :: .send :: line 3" data: no] { message="Failure"
, result=2147500037
, name="NS_ERROR_FAILURE"
,
If I have understood correctly, "authorization + Basic " in header tells the Glassfish-server, that basic-authentication will be done. After authentication it goes to REST-service and in my case returns json-object to HTML5-client. HTML5-client is running in localhost:8383 and the rest services are running in localhost:8080.
If I run secured rest-services straight in localhost:8080, it is working, so that is not the problem. The problem is that when I am using or trying to use rest-services from different domain localhost:8383, I get get the JS-error console.log('----ERROR IN ------Siging IN----------'); I am not 100 % sure, but I think that the problem is 401 unauthorized, so cross domain authentication is not working.
Shoud I insert crossDomain: true? I have seen it somewhere, maybe that can be the case?
In serverside I've got the filter:
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>util.CrossOriginResourceSharingFilter</param-value>
</init-param>
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
response.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "content-type");
return response;
}
QUESTIONS
1) is it possbile that if server is not configured for authentication and I still use the authorization-header breaks the app and cause the error?
2) What that JS-error means?
Cheers,
Sami

Related

Accessing Cross-Domain WCF-Webservice with jQuery or Javascript

I'm sorry to ask this question again, but I didn't find a fitting answer to my problem.
I try to build the following:
I want to connect to a WCF-Webservice with a standard Webpage. Both website and web service are hosted in an IIS on the same machine.
I enabled cross-domain to the web.config:
<webHttpBinding>
<binding name="webHttpBindingWithJSONP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
And my AJAX request:
$.ajax({
type: "POST",
url: config.endpoints.db.production + "AddData/",
data: JSON.stringify(data),
contentType: "application/json",
dataType: "json",
crossDomain: true,
// processData: true,
success: function(data, status, jqXHR) {
// alert("success..." + data);
// loadingVisible(false);
// loadingFinished = true;
},
error: function(xhr) {
alert("failure..." + xhr.responseText);
// loadingFinished = true;
// loadingVisible(false);
}
});
After firing the request I got an "Access denied"-Error in the visual studio from jquery.
After searching in the web I found out that this is a very common cross-domain problem, but I didn't find a solution. I tried to set "crossDomain: true" in the ajax-request, tried to use jsonp (which worked for my GET-requests) but nothing helped.
Is there a proper way to solve this? I read that this problem might be solved with an ajax authentication. Is that correct and how can I achieve that?
To solve the problem do the following
Create a Global.asax and add following to enable Ajax cross-domain POST
public void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST,OPTIONS");
if ((HttpContext.Current.Request.HttpMethod == "OPTIONS"))
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}
At your service set
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class YourserviceName : YourserviceNameInterface

Syntax Error Unexpected token only for Jelly bean phones

I have an HTML5 based android app. The app was working perfectly fine and was able to fetch data from the backend system. However, since today the app is reporting a weird error while fetching data SyntaxError Unexpected token and shows some gibberish character. This error is occurring only on phones having Jelly Bean (Android 4.2.1); it was working perfectly fine till last week and there has been no change in the code. In the below code the ajax call goes into the error section for Android 4.2.1.
function getData() {
jQuery.support.cors = true;
$.ajax({
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('X-SMP-APPCID', connectionID);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(appUser + ":" + appPass));
},
url: calURL, //calURL is the connection to backend
crossDomain: true,
dataType: "json",
processData: false,
xhrFields: {
withCredentials: true
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error fetching Data - " + errorThrown);
hideMainContent(false);
document.getElementById("data").innerHTML = "Error fetching data - " + errorThrown;
if(errorThrown.indexOf("Unauthorized") > -1){**// Invalid token reported here**
document.getElementById("setButton").innerHTML = "<p>Unauthorized error can occur if your password has expired or changed. Below option can be used to change application password to your new Password.</p><button onclick=\"changePassword()\" class=\"ui-btn style=\"margin:10% 25%;width:50%;\">Change Password</button>";
}
else{
document.getElementById("setButton").innerHTML = "<p>Temporary communication error. Please refresh after some time.</p>";
}
},
success: function(jsonData) {
},
});
return;
}
Any help in this regards is highly appreciated.
Thanks!

AJAX request not working on remote host

I've got an AJAX request which pulls the data from the form and POSTs it to an API. The weird thing is it works perfectly fine on localhost but fails silently when I upload to remote server. And I mean silently: the response code is blank, there's nothing in the logs. I've checked on Firefox and Chrome. jQuery is loaded, function is firing properly. The code is below:
function send() {
console.log("preparing");
var beacon = {
beaconID: $("#beaconID").val(),
name:$("#beaconName").val(),
campaignID:$("#campaignID").val(),
clientID:$("#clientID").val()
}
console.log("payload:");
console.log(beacon);
$.ajax({
type: 'POST',
url: '../beaconAPI/index.php/createBeacon',
data: JSON.stringify(beacon),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
console.log("done:");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
From the comments you posted
10:33:21.046 "{"readyState":0,"responseText":"","status":0,
"statusText":"error"}" addBeacon.html:34 10:33:21.046 "AJAX error: error : "
A status code of zero means one of two things:
You are running off file protocol
The page refreshed as Ajax call is made
Since you said this is on production, sounds like it is a case of #2.
So you need to cancel the action that is causing the page to refresh. Since you do not show how you call send, here is some basic ways of cancelling the action.
onclick="send(); return false"
onsubmit="send(); return false"
$("#foo").on("click", function(e) {
send();
e.preventDefault();
});

Cross domain jQuery ajax calls not working

I'm having trouble with this code and I can't seem to get it to work. The typical error that I get back for this call is a "Failed to load resource: the server responded with a status of 401 (Unauthorized) " .
$('#btnZendesk').click(function () {
$.ajax({
url: "https://flatlandsoftware.zendesk.com/api/v2/topics/22505987.json",
type: 'GET',
crossDomain: true,
xhrFields: {
withCredentials: true
},
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
timeout: 2000,
username: "test#test.com",
password: "test",
success: function (data, textStatus, response) {
alert("success");
},
error: function (data, textStatus, response) {
alert(data);
}
});
Problem is that the resource you are trying to access is protected with Basic Authentication.
You can use beforeSend in jQuery callback to add a HTTP header with the authentication details e.g.:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic XXXXXX");
}
Alternatively you can do it using jQuery ajaxSetup
$.ajaxSetup({
headers: { 'Authorization': "Basic XXXXX" }
});
EDIT
A few links to the mentioned functions
jQuery.ajaxSetup
jQuery.ajax
EDIT 2
The Authorization header is constructed as follows:
Username and password are joined into a string "username:password" and the result string is encoded using Base64
Example:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
I too got this problem and somehow all solutions from internet either failed or were not applicable due to client webservice restrictions (JSONP, XDR, CORS=true)
For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.
We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.
Hope it helps
<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
</iframe>
//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');
//The iframe receives the data using the code:
window.onload = function () {
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
var origin = e.origin;
//if origin not in pre-defined list, break and return
var messageFromParent = JSON.parse(e.data);
var json = messageFromParent.data;
//send json to web service using AJAX
//return the response back to source
e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
}, false);
}

How can I get the results of a JSON POST back

I'm posting this JSON from a form page
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js" type="text/javascript"></script>
<script type="text/javascript">
function poster()
{
var dataToPost = {grant_type: "password", username: dojo.byId("username").value, password: dojo.byId("password").value, redirect_uri: "http://localhost/default.html"};
var xhrArgs =
{
url: "https://localhost/api/did/authenticate?client_id=12345",
handleAs: 'json',
postData: dojo.toJson(dataToPost),
headers: { "Content-Type": "application/json; charset=UTF-8", "Accept" : "application/json" },
load: function(data, args)
{
alert("Data = " + data);
},
error: function(error, args)
{
alert("Error! " + error);
}
}
dojo.rawXhrPost(xhrArgs);
}
</script>
But I'm not able to get the JSON results from said POST. How can I get those results? Please help. The data I get on the load function is null
The script at https://localhost/api/did/authenticate needs to print or echo or write or otherwise return the JSON as text as it exits.
Turns out that what I was trying to do is not possible in JavaScript since I'm trying to do it from one domain into another... so the cross-domain implementation is not possible, unless I use an embedded flash object, or a proxy pass in my server. thanks for the help though...

Categories

Resources