Laurynas Mališauskas Laurynas Mališauskas - 1 year ago 127
PHP Question

Symfony3 AJAX request from iframe on the same domain does not save Session attribute

I use Symfony v3.0.6 on PHP 5.5.28 with OPcache Enabled.
Security for site administrators is managed by FOSUserBundle.

Site users visit a page where they are displayed a non Symfony form in an iframe from the same domain which makes an AJAX request to simple Symfony action:

public function validateAction(MailingList $mailingList, Request $request)
$email = $request->get('email');
$code = $request->get('code');
if ($mailingList->getCode() == $code) {
$response = new Response('', 200);
$securityManager = $this->get('security_manager');
$securityManager->grantAccess($request->getSession(), $mailingList, $email);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
$responseFailed = new Response('N2', 401);
$responseFailed->headers->set('Access-Control-Allow-Origin', '*');
return $responseFailed;

As you can see i call my custom service SecurityManager where i add an attribute to the Session:

public function grantAccess(Session $session, MailingList $mailingList, $email) {
0 => hash('sha256', $email.$mailingList->getCode()),
1 => $email

The AJAX call succeeds and the whole page is reloaded with

After the reload Symfony debug toolbar does not show any signs of attribute set in the previous Request.
I have also tried to use Cookies, but with no success. The same pattern remains.

Answer Source

Problem solved and the short lesson - do not use iframes or frames. ever.

<iframe> and the main page have separate PHP sessions (checked the session IDs). So the buggy process looks like that:

  1. AJAX request is sent from <iframe>
  2. Symfony action updates attributes in <iframe> Session
  3. Response 200 comes back and JavaScript reloads the whole page (window.reload()).
  4. On page load main page Session gets checked for token and obviously there is none there, so the login form gets displayed.

Important note!

Some older browsers or new browsers, but with less strict security/privacy settings may use the same session for the main page and <iframe>.

This was the main reason why it took so long for me to hunt that bug down. It looked like the code behaves inconsistently.

After dropping the use of >iframe> the code worked like a charm.

Thanks everyone for your ideas. Hope this saves some time for other fellow programmers in the future.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download