Backbonejs - CORS error - backbone.js

I have a REST service sitting at http://restservice.net. I am implementing a client for this service in backbone. The client is simply an html file (for bootstrapping the application) and bunch of js files holding my backbonejs code. I am hosting these files on another site http://client.net.
My backbonejs code is calling into http://restservice.net but now allowed due to same origin policy. I have already looked at other SO questions that talk about how I can only talk to http://client.net.
Do I have to redirect every request through http://client.net. I see that as inefficient. What's the point in using a client side MVC framework then? Am I missing something here?

You have two options: JSONP and CORS both of these demand that your http://restservice.net server is setup to suppor the protocols. Forcing backbone to use JSONP simply requires you passing an option to Backbone.sync. One way to do this is like this:
sync: function(method, model, options){
options.dataType = "jsonp";
return Backbone.sync(method, model, options);
}
The problem with JSONP is that you can only make GET requests, so your REST api is effectively read only. To get CORS working you simply need to configure your api server to send back the proper headers . This would pretty liberal:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, PUT, DELETE OPTIONS
here is a pretty good run down on CORS. If you set that up, then things will pretty much work as usual.
If you don't have the ability to make changes to the server at http://restservice.net then you have no choice but to proxy all the requests to that service. This is definately inefficient but implementing is probably simpler than you would expect. One thing to consider is a reverse proxy

Related

Request and Response between two projects

I'm trying to work on 2 projects. The first one is mainly for client side (AngularJS+MVC) development and second is server side, including web APIs. I want to use web APIs as controllers.
I set the server side project as start-up project. Then set its URL (localhost:..../) as the URL of the controller, then ran the project. After that with the view in the browser, I ran my view, too. (From the client project). The request correctly gets to the API controller from the second project, but I didn't reserve any Response. I guess the problem is the difference between URLs.
What is your opinion? And what should I do, then?
What kind of response are you getting? 200 (OK) status or something else? you might be getting cross orgin request error, if you have not enabled CORS on the web api and you are making the api request from the client side of the Angular project.
Please don't mind my poor English.
Are two projects served on the same domain? If not, there maybe a cross origin request error. You can fix it by adding some headers, like this:
header('Access-Control-Allow-Origin','*');
header('Access-Control-Allow-Methods', 'GET,POST,DELETE,PUT,PATCH');
header('Access-Control-Allow-Headers','Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');

Why is CORS Disabled by Default?

Alright, first of all, I am absolutely aware that we have a bunch of answers on this and there is a plethora of articles on the topic. I just read these answers a second before typing this:
Why is CORS without credentials forbidden?.
Is CORS considered bad practice?
Etc. My particular situation is this - I just set up WebAPI2 for my practice project, the front end for which is running via gulp browser-sync. I have no idea how these ports get picked, but lets say the Web API is running on port http://localhost:1234/ and browser-sync generates the website on http://localhost:4321/. So I hit the API via angular's $http and get the famous CORS error (API controller method does get hit), so I am guessing it's the API returning not allowed. Edit: I fixed this via installing a CORS for Web API package via NuGet (Article Here) before asking this Q, just referencing for anyone who might need it later.
So, I was thinking, if I deployed this, ANY request would get denied, unless I am missing something. Or would it not be denied because of something I don't understand? Is disallowing CORS just a throwback from the MVC days? Or is there some purpose to it with APIs?
Maybe I am just ranting, but this confuses the **** out of me.
CORS is based on the response headers returned from the API. It is not the API that rejects responding to the request, the web browser explicitly disallows handling the response. The API will process the request as normal.
When dealing with anything other than a GET, CORS also requires a "preflight" request to the API first, to ensure subsequent requests are allowed. This amongst sending the headers back is what the Web API nuget package provides.
CORS is off by default for security purposes.

What is the main reason to use headers for authentication tokens?

Just getting up to speed with authentication in angular . What I read a lot is the usage of headers to pass in a token like here: $http Auth Headers in AngularJS
My question is with passing in the token for every request to the backend what are the main reasons to use headers? Is this just for a cleaner solution or is it for performance?
Using headers for this isn't an Angular thing, many APIs use these so that for example a server can determine if the client should be allowed access quickly by examining only the headers and not the request body. This allows better separation of concerns between authentication and authorization functions, and payload processing on the server.
Upstream servers (of which there may be many layers) can add and remove headers and generally route and authorize your request more efficiently than if this data were to be in the request body.
Headers also keep authentication data out of URL request parameters which looks cleaner but also stops authentication data appearing in browser history etc.
One downside could be that if you are making requests through a network proxy there's a chance that the proxy may strip some headers especially if they're non-standard names.
If your connection to server is HTTPS then HTTP HEADERS are also encrypted. Where as query params are not.

Angularjs proceed with server call even if CORS does not allow a header value

I have an AngularJS application that talks to various java services. In the application I have a global http header setting in an http interceptor. That means all the service requests from my application will get the header values.
Now the trouble is that all the services CORS settings won't allow this header value. Couple of services does, while others does not. The service calls to the servers that do not support the header fails, since the http interceptor always puts the header values.
Is there a better way to design, in the above said case, so as to avoid the issue stated?
Appreciate any help...
How about adding a response interceptor, looking for a 401 status? If you get a 401, attempt to do the same request again without the headers this time. If this succeeds, 'whitelist' this domain to make all following requests without the headers that you don't want.
Otherwise, if you have a limited number of services that you are making calls to, maybe whitelist them inside of your request interceptor? This would probably be easier, but it's not very elegant.

is it possible to intercept the response to an HTTP OPTIONS preflight in AngularJS?

I'm trying to implement a simple interceptor that allows me to display a message along the lines of "cannot contact the server" in my Angular app. However as the API is on a different host I'm dealing with CORS pre-flight OPTIONS requests.
I've found that if the API is unavailable Chrome dev tools shows a 503 on the OPTIONS request but Angular's $http interceptor catches a 404 response to the subsequent GET request. I believe this is because the OPTIONS response did not contain the required CORS headers so the GET is actually never performed.
Is is possible to intercept the OPTIONS response? If all I see is a 404 I can't distinguish "server down" from "no such resource".
You can't intercept this request by design - the browser is "checking up" on you, making sure YOU should be allowed to make the request.
We've used three solutions to work around this:
If the problem is that you're using a development environment like NodeJS, and your domain names aren't matching (that is, if you normally wouldn't need to deal with this in Production) you can use a proxy. The https://github.com/substack/bouncyBounceJS NodeJS Module is an easy to use option. Then your Web service request domain will match the domain your page is on, and the check won't be triggered. (You can also use tricks like this in Production, although it can be easily abused!)
Also for temporary use, you can use something like Fiddler or Charles to manipulate the request by faking the required headers, or tell your browser not to check them (--disable-web-security in Chrome).
If you have this problem in Production, you either need to legitimately fix it (adjust the Web service handler to add the required headers - there are only two), or find a way to make the request in a way that doesn't trigger the check. For instance, if you control both the source and target domains, you can put a script on the target that makes the requests to itself. Run this in an IFRAME, invisibly. Then you can use things like postMessage() to communicate back and forth. Large services like Facebook use "XHR bridges" like this for the same reason.

Resources