views:

93

answers:

2

I'm building an API that will use JSON. The primary use for this API will be AJAX in a browser but it may also be used server-side by user's PHP scripts, etc.

There are 2 ways I can do this (I think):

  1. Build the API so that it uses HTTP headers to set a session cookie and retrieve all data for maintaining state by using the COOKIE['session_id'] (pseudo code)
  2. Build the API so that it returns session_id and allows the user's JavaScript code to set its own cookie for session_id

I'm a little lost in general. Which way will be more secure (CSRF, etc), easily understood by developers, easier to make server-side changes without telling users they have to update their code.

Also, do you recommend using JSON-RPC spec, and if so, do one of these methods better support JSON-RPC?

Any help is much appreciated.

A: 

The session should be handled by your application backend, which should create the session and create the related cookie. From one point of view you won't be dealing with session handling in your AJAX calls because the browser automatically sends out the cookies it has assigned for a website.

While using your API from outside the browser, there are various ways people could handle the requests. Cookies are handled unobtrusively by HTTP libraries like cURL.

My question is why do you need sessions for the API, are you only using it for authorization?

mhitza
@mhitza - Im calling it a "session_id" but it's really just an object id for the object that will be edited by the end-user (since they'll be editing the same object for a few minutes).
orokusaki
+3  A: 

I was faced with the same problem (how to do sessions for a JSON-RPC based web service infrastructure). I ended up using a URL parameter for the session. My reasoning:

  • Using cookies means cookies end up being fundamental to the operation of the app. I prefer the option of disabling cookies entirely and still having the app work.
  • HTTP headers seemed like they could get problematic when addressing the JSON-RPC service from a non-web environment (e.g. from a native windows app).
  • Using the session as the first argument to every method is something that I find just plain ugly.

Since the URL with the session parameter is only used to call web service methods, and therefore doesn't appear in the URL bar of the browser, I don't think there are actually security implications of working this way. But security is a tricky thing, so I'm sure someone will be along in a bit to correct me.

Joeri Sebrechts
Making the API work without cookies is definitely going to make developers happier. Including a "session_id" may be uglier, but it's more in keeping with the fact that HTTP is stateless and should be treated that way.
Jacob
@Jacob - thanks as well!
orokusaki