URL not allowed by Access-Control-Allow-Origin - ajax

I am trying to implement OAUTH for accessing Flickr APIs. My AJAX call to flickr.com keeps failing.
Sample Error Message:
XMLHttpRequest cannot load http://www.flickr.com/services/oauth /request_token?oauth_callback=oob&oauth…signature_method=HMAC-SHA1&oauth_timestamp=1368375405647&oauth_version=1.0. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.
Initially I used chrome and read the html file as file://path. I used to get the error 'null not allowed by access-control-allow-origin'. I solved this problem by copying the html file to 'local IIS server', 'local python webserver' and then a 'remote webserver'. I created python web server using > python -m http.server 8080'
I realize my cross browser call to flickr.com using XMLHttpRequest is failing. I tried by various solutions suggested in this forum:
Using newer Chrome 26.0.1410.64 m, which I guess supports CORS
I launched chrome with --disable-web-security
I created a web server using python -m http.server 8080 on local machine and then on a remote machine and copied the html file to the site
I copied file to a local MSFT IIS server
I defined URL in etc/hosts file to avoid numeric IP
I still get the same error (with relevant URL in the error message)
code clipping:
urlString="http://www.flickr.com/services/oauth/request_token?"+
"oauth_callback="+"oob"+'&'+
"oauth_consumer_key="+consumerKey+'&'+
"oauth_nonce="+nonce+'&'+
"oauth_signature="+esignature+'&'+
"oauth_signature_method="+macAlgorithm+'&'+
"oauth_timestamp="+timeStamp+'&'+
"oauth_version=1.0";
$.ajax({
url: urlString,
success:function(data){
alert(data);
}
});

In order to CORS work, both ends must enable it.
The first end is the browser, and, as you are using Chrome 26.*, yours is ok.
The second end is the server:
Before making a GET request to a domain different than the one the page is on, the browser sends an OPTIONS request to that domain. In response to this request, the server should include some headers that tell if a cross-domain request (GET, POST or other) is allowed.
One of those headers is Access-Control-Allow-Origin.
So when you run your page from your file system (file:// "protocol"), the OPTIONS means something like "Flickr, can I make a cross-domain call to you? I'm calling from null". Flickr does not recognize that domain as allowed and returns the error you are getting.
Same way, when you run your page from your local server, the OPTIONS says "(...) I'm calling from localhost:8080". Flickr does not recognize that domain as allowed as well.
The solution:
I don't know the Flickr oauth service, but I know that, as any other service, to make a CORS call to it, the page must be in a domain allowed by it. From your tests, I'm guessing Flickr does't allow many other domains.
But... an alternative to CORS is JSONP. I did a little research, Flickr oauth seems to support it.
Check this page for details: http://www.flickr.com/services/api/explore/flickr.auth.oauth.getAccessToken
There's another question talking about that specific subject:
Is JSONP supported in the new Flickr OAuth API?
About JSONP, this can get you started: How to make a JSONP request from Javascript without JQuery?

It is not possible to implement Oauth 1.0 through just javascript without any server side script. Since the flickr's new authentication process is based on Oauth 1.0a. You got to use a server-side script.
I tried to send the token request using JSONP in FireFox with CORS on(using a third-party add-on) and it worked fine. But without using any add-ons, it's not possible as the response from flickr is in text format(not in a JSON format) and the request fails.
You can either use server-side code for token request. OR Use the deprecated flickr API for authentication.

Related

How to secure web api with Identity Server 3

I'm building an MVC web app that uses the openID Connect hybrid flow to authenticate with Identity Server 3. The MVC web app contains jQuery scripts to get async JSON data from een ApiController. That ApiController is part of the same MVC web app.
I don't want that everyone is able to access the data from the API, so I want to secure the API as well. I added an [authorize] attribute to the ApiController. When requesting the API with a JQuery ajax request I get the following error message:
XMLHttpRequest cannot load
https://localhost:44371/identity/connect/authorize?....etc.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:13079' is therefore not allowed
access. The response had HTTP status code 405.
But, when I do a request to the API method directly in browser, I will be correct redirected to the Login page of Identity Server..
So, what's exactly the problem here? I read something about that requesting the /authorize endpoint is not allowed via 'back-channel', but I don't understand what's the difference between 'front-channel' and 'back-channel'. Is it possible that I mixed up the wrong OAuth flows? Is the Hybrid flow not the correct one maybe?
I also find out that the API is often a seperate app, but is it always neccessary / best-practice to build a seperate API app that for example requires a bearer token?
Please point me in the right direction about this.
The authorize method on your identity server does not allow ajax calls. Even specifying CORS headers is not going to help you in this particular case. Perhaps you could return a forbidden response instead of a redirect and manually redirect the client to the desired location via window.location
You need to allow your IdentityServer to be accessed from other domains, this is done by allowing "Cross Origin Resource Sharing" or CORS for short. In IdentityServer the simplest way to allow this is in your Client configuration for your Javascript Client, see this from the IdentityServer docs on CORS:
One approach to configuing CORS is to use the AllowedCorsOrigins collection on the client configuration. Simply add the origin of the client to the collection and the default configuration in IdentityServer will consult these values to allow cross-origin calls from the origins.
The error you're seeing is the browser telling you that when it asked IdentityServer if it allows requests from your Javscript client, it returned a response basically saying no, because the origin (http://localhost:13079) was not specified in the "Access-Control-Allow-Origin" response header. In fact that header wasn't in the response at all meaning CORS is not enabled.
If you follow the quickstart for adding a JavaScript client from the docs here all the necessary code is detailed there that you need for the Client config and to setup IdentityServer to allow CORS.

Issues accessing socialauth via ajax

I am developing a server side web app using spring socialauth library by 3 pillars lab.
When accessing this web app using href in an anchor tag, I am able to invoke the 3rd party application (in my case, facebook) page.
But when i tried calling it using jquery ajax I got "Allow origin header error". On searching for this error, I found out that this error is due to the ajax calling page and the URL, it is trying to call, being on different domains. I have changed the headers in my webapp as: "allow origin to *". After this, my webapp does not throw this "allow origin header" error but now 3rd party app is throwing this error.
I have tried two types of Cross domain ajax method :
JSONP: with this i am able to hit even 3rd party url via ajax but it is throwing an error
"Resource interpreted as Script but transferred with MIME type text/html"
As per my understanding, it is throwing error because this method expects JSONP as response instead getting text/html in response.
CORS (Cross-Origin Resource Sharing):
In this also, facebook is throwing allow origin header.
I want to make ajax call to facebook using my webapp that uses socialauth library and it should display facebook page. Plus i dont want to redirect it.
I am stuck at this. Please help.

Access-Control-Allow-Origin issue in XMLRPC request

Am working in Mobile App develoment using HTML5 + Phonegap. Currently am working a mobile App using XMLRPC and its working fine. (Android and iOS)
I need to work the same application as a website in browsers. (using HTML5).
But when am trying to Run my application on website i am getting this error :
XMLHttpRequest cannot load 'Client' URL'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost <http://localhost/>' is therefore not allowed access.
When am search experts says that use JSONP. But using same XMLRPC method can i work it ?
For example ;
For a Login purposes am using ;
$.xmlrpc({
url: 'http://clienturl/xmlrpc/common',
methodName: 'login',
params: [Database_name','user_name','Password'],
success: function(response, status, jqXHR) {
alert('success'); },
error: OnError
});
Its working fine as a Mobile Application.
But gets Access-Control-Allow-Origin cross domain issue when i am trying to run as a Website.
How can i fix this ?
By default the SOP (same origin policy) allows cross-origin requests, but it prevents receiving the responses of those requests. The Access-Control-Allow-Origin in your error message is a CORS (cross-origin resource sharing) header. It tells the browser that you allow reading the responses of a domain (your XMLRPC server's domain) by sending requests from another domain (your XMLRPC client's domain). So you have to send back CORS allow headers from your server if you want to call it with AJAX.
note: CORS won't work in old browsers.
Possible solutions:
If you call http://clienturl/xmlrpc/common from http://localhost then the
response.header('Access-Control-Allow-Origin', "*")
is one not so secure solution according to this: Origin http://localhost is not allowed by Access-Control-Allow-Origin
But you can always add another hostname (e.g. http://client.xml.rpc) for your client, for example by windows you can modify the hosts file and add a binding using the IIS server.
I don't recommend this solution, because it is a security risk with the allow credentials header.
Another more secure options is to make a list of allowed hosts, check from which host you got the actual request, and send back the proper header:
if (allowedHosts.contains(request.host))
if (request.host== "http://localhost")
response.header('Access-Control-Allow-Origin', "null");
else
response.header('Access-Control-Allow-Origin', request.host);
else
response.header('Access-Control-Allow-Origin', server.host);
This is the proper solution with multiple hosts, because if you allow credentials for *, then everybody will be able to read and write the session of a logged in user.
By http://localhost and file:/// IRIs you have to use the null origin. I am unsure about other protocols, I guess in the current browsers you have to use null origin by them as well.

IE throwing Error on regular ajax request

I have an issue with a Facebook Page Tab I have built.
The website functions perfectly fine in Chrome and Firefox but I have an issue when I try to do something simple in IE.
[BASE URL: http://domain.com/]
[REQ URL: http://domain.com/request]
What I am trying to do is make a simple ajax request from my server BASE URL to my server again on REQ URL, In Chrome or Firefox I get the expected result, IE however I get a couple of errors and warnings.
Warnings are as follows (without sensitive domain information)
SEC7118: XMLHttpRequest for https://www.facebook.com/dialog/oauth?client_id=APP_ID&redirect_uri=URL_ENCODED_REDIRECT_URI required Cross Origin Resource Sharing (CORS).
SEC7119: XMLHttpRequest for https://www.facebook.com/dialog/oauth?client_id=APP_ID&redirect_uri=URL_ENCODED_REDIRECT_URI required CORS preflight.
Errors are as follows
SEC7120: Origin http://domain.com not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.
I have done a lot of research on these errors and I know that they are related to Cross Origin Control and making requests from one domain that does not match another. The strange thing is though that both my domains are the same so CORS should not apply. I can't figure out what I'm missing. I have read at least 20 articles on stack overflow with none of them able to address my problem exactly.
The /request/ in the REQ_URL is a method that gets called from a controller, all I need is for this method to be called there is nothing special about it, it's a simple PHP function.
function request() {
return 'you win!';
}
The ajax is using jQuery to make the request specificly the $.get method this is my code:
$.get('/request', function(response){
console.log(response);
});
I get no response.
I have also tried this with $.ajax and calling the complete method I get a text status type returned of 'error' I expect this to be the result of the error above.
I have read and understand the articles as follows:
Cross-origin resource sharing
Same-origin policy
According to the Same-origin policy I shouldn't be bound to CORS and my get request should just work or am I missing something.
Any help is appreciated.
['UPDATE']
I have identified that the above errors occur only when inside facebook (Facebook Page Tab) this "I think" is a result of the iframe being from the domain "http://static.ak.facebook.com/" and my domain "http://domain.com" This breaks the Same-origin policy rule. Very annoying because when the ajax calls are made they are sent from "http://static.ak.facebook.com/" to "http://domain.com" there in I am getting Cross-origin policy errors.
I still don't know how to fix this problem.
Not many up votes, Not many views.
I found the issue, and the solution.
For my particular case I was using sessions to handle information on the server side, what was happening was the session was not persisting in IE witch was causing some of my other code to redirect he ajax request to another domain (facebook.com) resulting in the cross domain request error you see above.
The Solution:
I found out that IE doesn't like to pass sessions around through ajax but you can tell it that it would be a good idea do follow suit to the other modern browsers and that was as simple as adding a P3P header.
Add this to your code before sending a request and the session variables should be sent in the requests.
header('P3P: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
I ended up rewriting my application without so many dependicies on the sessions but this was definatly a good learning point about IE and how it handels sessions through ajax.

AJAX request to https php server from Firefox and Chrome extensions

I'm working on extensions for Firefox and Chrome. The data used by my extensions is mostly generated from ajax requests. The type of data being returned is private, so it needs to be secure. My server supports https and the ajax calls are being sent to an https domain. Information is being sent back and forth, and the extensions are working correctly.
My questions are:
Do the extensions actually make secure connections with the server, or is this considered the same as cross domain posting, sending a request from a http page to a https page?
Am I putting my users' information at more risk during the transfers than if the user were to access the information directly from an https web page in the browser?
Thanks in advance!
The browser absolutely makes a secure connection when you use HTTPS. Certainly, a browser would never downgrade the security of your connection without telling you: it will either complete the request as written or it throw some sort of error if it is not possible.
Extensions for both Chrome and Firefox are permitted to make cross-domain AJAX requests. In Chrome, you simply need to supply the protocol/name of the host as a permission in your manifest.json. In Firefox, I think you may need to use Components.classes to get a cross-domain requester, as described in the MDN page for Using XMLHttpRequest, but I'm not 100% sure about that. Just try doing a normal request and see if it succeeds; if not, use the Components.classes solution.

Resources