JSON API intended for JavaScript use - handle session data server side, or in browser?
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):
- 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) - Build the API so that it returns
session_id
and allows the user's JavaScript code to set its own cookie forsession_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 u开发者_如何学Cpdate 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.
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.
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?
精彩评论