'Apply session id from request header

I am not sure if this is possible in Symfony so I came up with a question. The high-level scenario is:

  1. A request on the API (built in Symfony) must return the session-id on the response body
  2. The origin of request must include the returned session-id on its header for its succeeding request
  3. The API must check if the request headers has the session-id, if it does it must set that session on the Symfony session

For testing purposes, I am using two REST client for browser instance:

  • Postman (Chrome)
  • HttpRequester (Firefox)

Here is the approach on code that I did:

The request from Postman:

POST http://path.domain/api/url/
Content-Type: application/json
{
    "key": "value"
}

Using HTTPFoundation Session, I set a session by:

$session = new Session();
$session->set('session-id', $session->getId());
$session->set('timestamp', time());

Then return it, here is the response:

200 OK
Content-Type:  application/json
{
    "session-id": "1a69f956b8efc5ab465356e3257a3230",
    "timestamp": 1487850859
}

Now, to simulate another response from different instance, I use HttpRequester but with the session-id on the header:

POST http://path.domain/api/url/
Content-Type: application/json
{
    "key": "value",
    "session-id": "1a69f956b8efc5ab465356e3257a3230"
}

By having a different request instance, I am expecting that Symfony will generate new session (new timestamp value). But for my case, I wanted to set the session id with the one in the request header, so I can access the previous timestamp as returned in the previous response.

I created a kernel event so I can intercept the request and do the checking if the request has session-id then do the setting of session.

// Get all PHP global variables
$request = Request::createFromGlobals();

// Check if the request
if ($request->headers->has('session-id')) {
    $session = new Session();
    $session->setId($request->headers->get('session-id'));
}

However, if I do this I get the error:

"error": {
    "code": 500,
    "message": "Internal Server Error",
    "exception": [
      {
        "message": "Cannot change the ID of an active session",
        "class": "LogicException",
        ...

What did I miss? Is this possible?



Solution 1:[1]

Have you tried something like this:

if ($request->headers->has('session-id')) {
    $session = new Session();
    $session->start();

    $sess = $session->get('session-id');
    $session->set('session-id', $sess);
    ...
}

I saw in the documentation there is a get function, but I normally don't use sessions so I don't know if this will work or not.

Can you try it?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alvin Bunk