Correct me if I am wrong: In a traditional web application, the browser automatically appends session information into a request to the server, so the server can know who the request comes from. What exactly is appended actually?
However, in a API based app, this information is not sent automatically, so when developing an API, I must check myself if the request comes from an authenticated user for example? How is this normally done?
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.
In a typical browser-server case; the browser manages a list of key/value pairs, known as cookies, for each domain:
Set-Cookie
HTTP response header.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.
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.
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
Set-Cookie
HTTP response header, inside the response body (XML/JSON auth response).00112233445566778899aabbccddeeff
with client/user #1337
.Cookie
request header, a ?sid=00112233445566778899aabbccddeeff
param(*).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.