Is it necessary for Server to allow/configure CORS - ajax

I am trying to perform an AJAX request from my site which is deployed on 'HTTPS' protocol. but the request I am making to is deployed on 'HTTP' protocol.
So I am getting the following error:
This request has been blocked; the content must be served over
HTTPS
My Request is as follows:
$.ajax({
url: "http://testsite/service/process.php",
type: "POST",
data: { service: '#service', id: '#id' }
});
Is there any way/trick to bypass this error/issue without changing
anything at ServerSide (http://testsite/) or Is it necessary to
ENABLE/CONFIGURE C.O.R.S on Server Side because I have no controll over Server Side.

Alternatives to CORS
If your web application must run in browsers that do not support CORS or interact with servers that are not CORS-enabled, there are several alternatives to CORS that have been utilized to solve the cross-origin communication restriction.
JSONP. This is a technique that exploits the HTML script element exception to the same-origin security policy. Script tags can load JavaScript from a different domain and query parameters can be added to the script URI to pass information to the server hosting the script about the resources that you wish to access. The JSONP server will return JavaScript that is evaluated in the browser that calls an agreed upon JavaScript function already on the page to pass server resource data into your page.
OpenAjax Hub. This is an JavaScript Ajax library that allows integration of multiple client-side components within a single web application. Trusted and untrusted components to co-exist within the same page and communicate with each other as long as they all include the OpenAjax Hub JavaScript library. The framework provides a security manager to allow the application to set security policies on component messaging. Iframes are used to isolate components into secure sandboxes.
easyXDM. This is a JavaScript library that allows for string-based cross domain communication via iframes. It works on the same principals as OpenAjax Hub but does not have the security manager component.
Proxied Iframe. This do-it-yourself technique involves including an iframe on your page from the domain you wish to communicate with. This assumes that you are able to host pages on this other domain. The JavaScript running in the iframe serves as a rest proxy to the server containing the resources you wish to access. Communication between your application and the rest proxy will take place using post message. Post message is part of the HTML5 standard, but there is also a jQuery implementation for non HTML5-compliant browsers.

Related

Why is AJAX unsecure?

I'm new to JS and AJAX, and one day, I tried a cross-domain AJAX request. After some researchs, I found out that AJAX could not work over cross domains (natively) because it is unsecure.
From Wikipedia: " This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model. "
But how could an AJAX request access to "sensitive data", while you can't with default HTTP?
An AJAX request is an HTTP request.
AJAX stands for Asyncronous Javascript And XML. It's kind of named that, after the first browser-based javascript HTTP client API, XMLHttpRequest.
HTTP requests are not inherently insecure, but certain things might make HTTP requests problematic.
A big one related to 'Ajax' requests is that, in the past at least, a HTTP request can carry session/cookie information.
This means that if Ajax requests were not restricted in browser sandboxes (cross-domain), it could mean that the owner of Site A, could make a request to Site B on behalf of a user.
Example: You're logged into a popular social network. Your browser uses a cookie to identify your logged in session. I send you a link to evil.example.org. If cross-site restrictions didn't exist, I could now make a HTTP for you + your session to the social network and act on your behalf.
However, this is not the end of this story. It is possible to do cross-site requests. This is called a CORS requests.
BUT: the way this works is that the owner of the site that you want to make a request to, has to allow in. In our previous example that means that the social network needs to explicitly allow "evil.example.org" to make these kind of requests.
The way this site gives you permission is via CORS headers.
Other ways to work around it is via:
Frames that are hosted on the site you're trying to access. (with specific code)
A proxy you control.
If the server you're trying to access delivers its content in a very specific way. (again, you need control of the target server).
If you control the target server, your best options is to just use CORS though. If you don't your best bet is to setup a proxy you control.

Ajax login to a website and follow redirect

I want to login to a website and follow redirection whit ajax or XMLHttpRequest or any thing else exept php.
Actually whene i try to do it, i have error "302 Moved Temporarily" but the webpage is the right page so i don't know why i get this error.
The website is an external website (not on my server).
This is my code :
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: "http://website/index.php",
data: { username: "myuser", password: "123456" },
success: function(data) {
console.log("success ", data.response);
},
error: function(data) {
console.log("error ", data.error);
},
dataType: "html"
});
If you try use ajax outside your domain, you will probably get this error message:
XMLHttpRequest cannot load http://www.example.com/path/filename. Origin
null is not allowed by Access-Control-Allow-Origin.
The reason you get this error message is because of the Same-origin policy. The policy permits scripts running on pages originating from the same site to access each other's data with no specific restrictions, but prevents scripts access to data that is stored on a different domain.
This could be a problem if you are trying to access publicly hosted data, but there are ways around it.
Here is the list of methods:
Implement CORS (Cross-Origin Resource Sharing)
Use JSONP (JSON Padding)
Use postMessage method
Setting up a local proxy
CORS (Cross-Origin Resource Sharing)
CORS is a mechanism that allows resources on a web page to be requested from another domain outside the domain the resource originated from. In particular, JavaScript's AJAX calls can use the XMLHttpRequest mechanism. Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request. It is more useful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests.
JSONP (JSON Padding)
JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on <script> tags.
Because of the same origin policy, we can not make cross domain AJAX requests, but we can have <script> tags that load javascript files from other domains. JSONP uses this exception in order to make cross domain requests by dynamically creating a <script> tag with necessary URL.
postMessage method
window.postMessage method is part of HTML5 introductions. It allows communication between window frames without being subject to same origin policy. Using postMessage() one can trigger a message event with attached data on another window, even if the window has different domain, port or a protocol. The frame where the event is triggered must add an event listener in order to be able to respond.
Let's see an example. Assume, we are on http://example.com (1) website and would like to make a request to http://example2.net (2) domain. We first must obtain a reference to (2) window. This can be either iframe.contentWindow, window.open, or window.frames[]. For our case it's best to create a hidden iframe element and send messages to it.
Setup local proxy
This method overcomes same origin policy by proxying content on another domain through itself. Thus making cross-domain issue irrelevant. To use this method you will either a) setup your server as a reverse proxy to fetch content from another server or b) write a script that would do that.
This cross domain querying solution works because you actually loading content from your own domain. You request the URL and the proxy script on your server loads the content and passes it over to you.
http://www.ajax-cross-origin.com/how.html You can visit this link if you want to learn about these methods in details. There is also a jquery plugin named ajax cross origin to tackle similar issues.

Enabling CORS on the client side

I'm creating a web appliacation that will run on a server that I can not manage nor modify in any case.
Within that application, I need to exceute a AJAX call to a different server.
This will always be blocked by the 'Same Origin Policy'.
Where server01.test.net is the webserver and mail.test.net is the second server.
Is there a way to enable CORS by any means in the client side, as I'm not able to add the 'Access-Control-Allow-Origin "*"' on the server. Or any other workaournd?
Thanks
CORS is an option with the SERVER. In no way client can by themselves enable CORS.
If client would have been allowed to do that, the whole purpose of CORS would be defeated.
If the server you are calling does not support CORS, you will not be able to make the request to the third-party server using AJAX.
You will have to resort to setting up a pass-through AJAX route in your application. The client (browser) makes a request to your AJAX route which proxies the call to the third-party server and returns the result. Because the third-party request is happening on the server rather than the browser, Same Origin Policy doesn't apply.
This approach means there will be an additional request that wouldn't be necessary if you could use CORS, but there really isn't another option.

Hosting two websites on same domain

I have two apps named opentripplanner-webapp and opentripplanner-api-webapp. I had successfully deployed them on local tomcat server. Apps has url as http://localhost:8080/opentripplanner-webapp and http://localhost:8080/opentripplanner-api-webapp. When i deployed apps on appfog , they give me different domains for both apps. The problems is that my apps use ajax request and responses which does not work on cross domains. I am searching for two days to find any solution but didn't find any suitable solution. Kindly guide me.
Thankss
Here's a couple of options for you:
Use JSONP (JSON with Padding). You would have to write your api so it supports this protocol, but it shouldn't prove too difficult.
Create both opentripplanner-webapp and opentripplanner-api-webapp so they support Cross Origin Resource Sharing. This means that your webapp sends an Origin header in the request, and the server responds with an Access-Control-Allow-Origin header, and if they match, the browser accepts the request. This is however not supported by all browsers, although most modern browsers do.
Use a proxy servlet in your opentripplanner-webapp that proxy requests to your API. You can "mount" this servlet at e.g. /api in the webapp, and it will forward all requests to opentripplanner-api-webapp internally. So you would send your AJAX requests to http://webappserver/api instead of http://apiserver. For the browser, this will look like an ordinary same origin request. This will work in all browsers, but might require some more setup.

Accessing Web Services via AJAX?

Is it possible to directly access third party web services using Ajax? Mostly I've seen that the website I'm visiting handles it on its server and then transfers the processed/unprocessed data to client browser. Is this always the case?
(yes, almost always)
Typically, when you're trying to accomplish accessing third party web services a proxy server is used to access those services. You can't reach external third party web services because they exist on separate domains and you run into the "Same Origin Policy"
Now.... there are methods for doing cross-domain ajax, but the service you are accessing must support it (there are restrictions on what kinds of data can be returned and how the requests are formatted due to the way cross domain ajax works)
A simple way to do this is indeed by using some sort of server-side proxy for your request. It works like this. You do the Ajax request to your own domain, lets say proxy.php. proxy.php handles your request, forwards it to the 3rd party service and returns te results. This way you don't get the cross-domain errors. You can find multiple examples of these simple proxy's by using the magic Google.

Resources