Authentication, Authorization and Session Management in Traditional Web Apps and APIs

HTTP Protocol is stateless by design, each request is done separately and is executed in a separate context.

The idea behind session management is to put requests from the same client in the same context. This is done by issuing an identifier by the server and sending it to the client, then the client would save this identifier and resend it in subsequent requests so the server can identify it.

Cookies

In a typical browser-server case; the browser manages a list of key/value pairs, known as cookies, for each domain:

  • Cookies can be managed by the server (created/modified/deleted) using the Set-Cookie HTTP response header.
  • Cookies can be accessed by the server (read) by parsing the Cookie HTTP request header.

Web-targeted programming languages/frameworks provide functions to deal with cookies on a higher level, for example, PHP provides setcookie/$_COOKIE to write/read cookies.

Sessions

Back to sessions, In a typical browser-server case (again), server-side session management takes advantage of client-side cookie management. PHP’s session management sets a session id cookie and use it to identify subsequent requests.

Web applications API?

Now back to your question; since you’d be the one responsible for designing the API and documenting it, the implementation would be your decision. You basically have to

  1. give the client an identifier, be it via a Set-Cookie HTTP response header, inside the response body (XML/JSON auth response).
  2. have a mechanism to maintain identifier/client association. for example a database table that associates identifier 00112233445566778899aabbccddeeff with client/user #1337.
  3. have the client resend the identifier sent to it at (1.) in all subsequent requests, be it in an HTTP Cookie request header, a ?sid=00112233445566778899aabbccddeeff param(*).
  4. lookup the received identifier, using the mechanism at (2.), check if a valid authentication, and is authorized to do requested operation, and then proceed with the operation on behalf on the auth’d user.

Of course you can build upon existing infrastructure, you can use PHP’s session management (that would take care of 1./2. and the authentication part of 4.) in your app, and require that client-side implementation do cookie management(that would take care of 3.), and then you do the rest of your app logic upon that.


(*) Each approach has cons and pros, for example, using a GET request param is easier to implement, but may have security implications, since GET requests are logged. You should use https for critical (all?) applications.

Leave a Comment