Vukoje.NET

Vukoje's blog about software development

Cross domain RESTful API calls?

Maybe you started moving more of your web app logic to client and relying on RESTful services for client-server communication knowing that someday other people will be able to reuse these services as remote API to you app. When I did, I knew that there was a problem with calling restful services from other site’s JavaScript because of the same origin policy that forbids browser to make cross domain Ajax calls, but I also knew that all the major web sites allow restful services consuming from JavaScript.

I investigated a bit and here are alternatives I found for this problem.

JSONP

JSONP is browser hack that became standard solution for cross domain Ajax calls. Browser is hacked by pretending that service is static JavaScript file. In order for this hack to work, server must support JSONP, which means you might be required to alter your services a bit.

Main issue with JSONP is that it doesn’t support HTTP POST (only HTTP GET). Another potential problem with JSONP is that is not asynchronous, which means that it would probably block browser which would lead to poor user experience.

CORS

Cross-origin resource sharing (CORS) is new standard that allows cross-domain Ajax calls. Main issue is that not all main browses are supported. Biggest problem is partial support in IE8/9 of which next limitations are biggest problem:

  • Only text/plain is supported for the request's Content-Type header
  • No authentication or cookies will be sent with the request

Server Proxy

Another alternative would be to use server proxy that would execute cross-domain request. In other words, do cross-domain request on server instead in browser because server doesn’t have Same-origin policy limitation. The disadvantage is additional work for your clients that must code server proxy instead of consuming your API right from JavaScript.

cqrs-proxy

iFrame integration

Although iFrames have cross domain restrictions like Ajax, they are much more flexible, so hidden iFrame can be used to enable cross-domain Ajax. 3rd party web page could load our special iFrame for that could execute Ajax calls in behalf of 3rd party page because it is on same domain as our API, and then it can send data back to page. For cross origin iFrame communication Window.postMessage can be used or easyXDM library if older browsers need to be supported.

cqrs-ifrmae

Resources

Comments (14) -

  • Niksa

    10/22/2014 2:06:02 PM | Reply

    If you are having server with REST API and others want to consume it from Javascript, shouldn't you develop Javascript wrapper which will encapsulate access to server REST API. This way a person would just need to include your Javascript from remote server and interact with it ?

    Cheers,
    Niksa!

    • Vukoje

      10/22/2014 3:01:31 PM | Reply

      Hey Niksa! Smile

      I don't think that would work. If you load some JS from other server that JS still cannot communicate with server from which it was loaded without cross domain restrictions being applied. Please correct me if I'm wrong.

      On the other hand I was thinking of building JS wrapper that would encapsulate access to my API, but it would do it by loading iframe in back, and that iframe would contain other JS ready to execute actions to server in behalf of the wrapper JS. I hope that made sense Smile

      • Niksa

        1/14/2015 3:12:51 PM | Reply

        Hi Vukoje,

        yes I was assuming to bundle your js with some of described techniques for cross-domain of course. Back in the old days (2009 I think) I was implementing cross-domain communication protocol with plain js and iframe src hashtag... there should be some code remains in Responsability Smile

        Cheers!

        • Vukoje

          1/15/2015 12:37:39 AM | Reply

          Awesome!

  • Marko Tomic

    10/23/2014 3:54:51 AM | Reply

    Nice one Vukoje, keep going!

    On the topic, the problem I see is growing trend of puting more and more logic to JS which is everything but secure. At least, it can never be secure like inter-server communication since Javascript (including cookies) sent to the client is available for inspection and reverse ingeneering. Having that in mind as a general rule of thumb is: Cerfully think what API calls you will be exposing to be called from the browser.

    • Vukoje

      10/23/2014 4:30:11 AM | Reply

      Definitely true. Latest trend is single page app and with it exposing everything app does through API which can be quite scary Smile

  • Darko Veselinovic

    1/9/2015 11:31:07 PM | Reply

    There is nothing about OPTION requests. They go first, and they ask things, like: can I set this header, can i use this method, etc...
    If you make RESTful API, why you need to set cookie to the client? RESTfull api should not have a session or use cookies. RESTful api should be state-less.
    It is not true that only text/plain supported in CORS.  You need to allow CORS to use content type header, something like
    header('Access-Control-Allow-Headers: Content-Type')
    And one more thing about cookies and authentication, I don't like what type of api's ppl call RESTful. API is not restful if you use session/cookies to provide authentication.  RESTful API need to be <b>stateless</b>

    Cheers
    Darko

    • Vukoje

      1/10/2015 5:36:23 AM | Reply

      Hi Darko,

      I didn't mention OPTION requests because CORS wasn't working out for my problem. As for the text only support in CORS, that is only for IE 8/9 and I got that form linked resource (I didn't test it). If you found this not to be true please let me know, it is very useful info. I guess you are using CORS and that it is working out for you?

      I use cookies because I'm connecting to legacy system that requires it, so I don't really have any option there.

      On the subject of restuflness, I don't really use it nor like it. I use HTTP services (WebAPI, MVC...) or as some call it RPC style for RESTfull services, but if I called it like that nobody would not what I meant Smile

      Stateless is always a good option unless it is leading you to performance problems or more complex solutions (NoSql DB, distribuuted cache etc...) I know that now it is popular to hate session but I absolutely love it. Its simple and super fast, it knows when to cleanup itself. The real problem is that it was heavily misused in past.

  • Marko Tomic Toma

    1/10/2015 2:39:34 AM | Reply

    This stateless topic is an interesting one. Nowdays it's coming from more and more sources that web applications should go in direction being completely stateless, actually sessionless. The main reason for it is easier recovery and easier real-time scaling especially since NoSql databases came to our world. The less contextual data you keep on the server in memory, the easier is to recover and scale.

    However, even if I understand this "trend" and find it meaningful, so far I wasn't able to figure out how actually this works Smile. Previously there had to be an initial handshaking where session id/token/key is generated on the server and every subsequent call from client will include this key which was used on the server to verify that session with this key exists. If now you don't have session and cookies to keep track of clients, how authentication is being done? Is it in the way that client sends auth data with every call or there is another way?
    @Darko
    If you know for a good resource where this can be found nicely explained it would be nice if you could share it with us.

    • Vukoje

      1/10/2015 5:46:17 AM | Reply

      Session and server affinity WTF! Go to distributed cache and NoSql when you absolutely have to, not just because "session is bad".
      If Facebook has to scale insanely it doesn't mean each site should.

    • Darko Veselinovic

      1/10/2015 1:52:28 PM | Reply

      @Vukoje
      I was playing when I was student. I make mechanism for routing, so I add one 'magic' parameter called _method. If _method is passed, it's overrides method from HTTP header. So you can do POST/PUT/DELETE/PATCH. So I did not run into a problem, I use JSONP and CORS Smile

      I think that stateless is not performance problem, you also need some time to get user session by session id, and sessions need to be cleared after some time (session time out). When you use token, server does not need to have any mechanism for clearing, because he is stateless Smile

      @Marko Tomic Toma
      I don't have good resource at one place. I was making some 'mini restful framework' in PHP at college. I flipped through REST in practice (http://it-ebooks.info/book/393/), but most things I read on the internet. The guys from Codebehind (hello! Smile) referred me to right way, since I originally used the session, and my server was not stateless
      And you ask about authenticaion....
      Authentication can be done by using tokens, and there are a lot of ways. Token CAN BE encoded string, server know secret key, so he can decode token, and get expire date, user id, etc. Ofc, it is not good to place all things in the token so we don't increase HTTP header size, only the most necessary, like user Id. Client must store token somewhere, probably using webstorage with fallback on cookies, and pass to server in every request. Also, server need to provide client token expiration date and "renewal token", so client can know when to go to server and pass renewal token to get new token.
      Token => used to get/change resource
      Expiration date => client know when to get new token.
      Renewal Token => used to get new Token

      sry for bad english Frown

  • Dejan Beciric

    1/12/2015 4:41:04 AM | Reply

    I have nothing against sessions ofcourse, but let's be clear: if you have sessions you have state and API is not RESTful (which ofcourse is nothing bad).

    @Vukoje  "I know that now it is popular to hate session but I absolutely love it."
    Nooo, it is popular to call services RESTful no matter they are not Smile

    • vukoje

      1/12/2015 4:46:11 AM | Reply

      I am guilty as charged Smile

      What would you it and still expect everyone to understand what you mean? You have JSON services in .NET WebAPI or MVC that are stateful and are more RPC than RESTful.

  • Vukoje

    1/13/2015 3:19:10 AM | Reply

    @Dejan/Darko

    It seams that MS shares your strong opinions on REST and session. I had a hard time today enabling session in WebAPI. I'm glad for your comments, they will keep me on my toes when using sessin.

    The problem is summarised nicely here
    www.strathweb.com/.../

    "Yes, there are a lot of problems with using session in your ASP.NET applications. Moreover, by default, HTTP (and by extension, REST) is stateless – and as a result each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP.

    So if you are designing a proper API, if you are a REST purist, or if you are Darrel Miller, you definitely do not want to continue reading this article. But if not, and you find yourself in a scenario requiring session – perhaps you are using Web API to facilitate your JS or MVC application, and you want to sync the state of Web API with the state of MVC easily, or you simply want a quick and easy way to persist state on the server side – this article is for you."

Loading