Question

I am creating a web service that (in an attempt to be RESTful) does not use cookies. My scheme for authentication is as follows.

  • User POSTs username and hashed password (over HTTPS) to /sessions.
  • /sessions responds with the session ID as part of the response body.
  • User authenticates all further requests by appending ?session_id=[session_id] to the URL.

When implementing this, I would like to create a session ID, store it somewhere (file or database) and then manually insert the session ID as a part of the response body.

The existing session functions in PHP already do a lot of this (the ID generation and file storage), but I can't figure out how to only use those parts and not have the session ID sent to the user as a cookie.

Is this possible? Or do I need to implement my own session ID generation function (any tips?) and file/database storage?

Was it helpful?

Solution

You can disable the ini setting for session cookies.

ini_set('session.use_cookies', '0');
session_id($your_session_token);
session_start();

Example:

authentication api - .../sessions/

...
check username/password ... other things
...
ini_set('session.use_cookies', '0');
session_start();
$_SESSION['user_stuff'] = $stuff;
$_SESSION['other_things'] = $things;

...
print session_id() along with whatever else is needed in the response body

the actual service - .../some_other_service_url/?session_id=[session_id]

ini_set('session.use_cookies', '0');
session_id($_GET['session_id']);//I'm not sure where PHP will look for it by default and I'm too lazy to check, so I'm making sure its $_GET['session_id']
session_start();
if(!$_SESSION['user_stuff']) {
    session token is missing, invalid or expired. the client needs to reauthenticate
}

do some useful things
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top