3
votes

I've got a issue with a fresh symfony 2.4 installation where the security token is not saved after logging in. I've never had this issue before (though i've never installed symfony on the production server that I'm using now). For 2 days i've been trying to fix this issue and I think i've read every post related to this issue on the internet.

This I've checked thoroughly:
- Sessions. They are working fine. I'm able to set a variable in my session and reload the page, and then read the same variable from session. I've using the native memcache session handler using the following config:

framework: session: handler_id: session.handler.mc

services:
    session.memcache:
        class: Memcache
        calls:
            - [addServer , [%session_memcache_host%, %session_memcache_port%]]
    session.handler.mc:
        class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler
        arguments: [@session.memcache, {prefix: ""}]

- User entity. As i'm using the FOSUserBundle as the user provider i'm extended their user Model (i'm using doctrine) as stated in their documentation. Note the role i've added in the construct method to make sure my user has this role:

<?php

namespace MB\Emaizing\AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="emaizing_user")
 */
class EmaizingUser extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();

        $this->roles = array('ROLE_USER');
    }
}

Firewall / security settings. I'm protected the whole site, through the firewall 'secured_area', and added a firewall dev for correctly showing the web profiler toolbar. I've added exceptions for the /login (and also /login_check) routes. I've also added an exception for another route that shouldn't be secured. The users are logging in by using their e-mail address as login.

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false
            anonymous: ~
        secured_area:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_provider: form.csrf_provider
                always_use_default_target_path: true
                default_target_path: /
            logout: true
            anonymous: ~

    access_control:
        - { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/lpx, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, role: ROLE_USER }

- Logs. This is what the log is saying:

[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". [] []
[2013-12-11 10:46:46] request.INFO: Matched route "fos_user_security_check" (parameters: "_controller": "FOS\UserBundle\Controller\SecurityController::checkAction", "_route": "fos_user_security_check") [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
[2013-12-11 10:46:46] doctrine.DEBUG: SELECT t0.username AS username1, t0.username_canonical AS username_canonical2, t0.email AS email3, t0.email_canonical AS email_canonical4, t0.enabled AS enabled5, t0.salt AS salt6, t0.password AS password7, t0.last_login AS last_login8, t0.locked AS locked9, t0.expired AS expired10, t0.expires_at AS expires_at11, t0.confirmation_token AS confirmation_token12, t0.password_requested_at AS password_requested_at13, t0.roles AS roles14, t0.credentials_expired AS credentials_expired15, t0.credentials_expire_at AS credentials_expire_at16, t0.id AS id17 FROM emaizing_user t0 WHERE t0.email_canonical = ? LIMIT 1 ["[email protected]"] []
[2013-12-11 10:46:46] security.INFO: User "[email protected]" has been authenticated successfully [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "security.interactive_login" to listener "FOS\UserBundle\EventListener\LastLoginListener::onSecurityInteractiveLogin". [] []
[2013-12-11 10:46:46] doctrine.DEBUG: "START TRANSACTION" [] []
[2013-12-11 10:46:46] doctrine.DEBUG: UPDATE emaizing_user SET last_login = ? WHERE id = ? ["2013-12-11 10:46:46",5] []
[2013-12-11 10:46:46] doctrine.DEBUG: "COMMIT" [] []
[2013-12-11 10:46:46] event.DEBUG: Listener "Symfony\Component\Security\Http\Firewall::onKernelRequest" stopped propagation of the event "kernel.request". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse". [] []
[2013-12-11 10:46:46] security.DEBUG: Write SecurityContext in the session [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\FirePHPHandler::onKernelResponse". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\ChromePhpHandler::onKernelResponse". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener::onKernelResponse". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelFinishRequest". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelFinishRequest". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\Security\Http\Firewall::onKernelFinishRequest". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener::onKernelTerminate". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelTerminate". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". [] []
[2013-12-11 10:46:46] request.INFO: Matched route "mb_emaizing_app_homepage" (parameters: "_controller": "MB\Emaizing\AppBundle\Controller\DefaultController::indexAction", "_route": "mb_emaizing_app_homepage") [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
[2013-12-11 10:46:46] security.INFO: Populated SecurityContext with an anonymous Token [] []
[2013-12-11 10:46:46] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException". [] []
[2013-12-11 10:46:46] security.DEBUG: Access is denied (user is not fully authenticated) by "/var/www/vhosts/www.emaizing.com/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php" at line 70; redirecting to authentication entry point [] []
[2013-12-11 10:46:46] security.DEBUG: Calling Authentication entry point [] []

As you can see here the user is being authenticated correctly. However after the redirect, no security context is found so it's assumed that we are a anonymous user (web profiler toolbar is showing user as anon).

I've tried to find out what's going wrong by debugging: Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse()

/**
 * Writes the SecurityContext to the session.
 *
 * @param FilterResponseEvent $event A FilterResponseEvent instance
 */
public function onKernelResponse(FilterResponseEvent $event)
{
    if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    if (!$event->getRequest()->hasSession()) {
        return;
    }

    if (null !== $this->logger) {
        $this->logger->debug('Write SecurityContext in the session');
    }

    $request = $event->getRequest();
    $session = $request->getSession();

    if (null === $session) {
        return;
    }

    if ((null === $token = $this->context->getToken()) || ($token instanceof AnonymousToken)) {
        if ($request->hasPreviousSession()) {
            $session->remove('_security_'.$this->contextKey);
        }
    } else {
        $session->set('_security_'.$this->contextKey, serialize($token));
    }
}

when I var_dump the session after this line "$session->set('security'.$this->contextKey, serialize($token));" I can see that the security token is added to the session. However it's not there after redirecting to the following page (default_target_path in firewall).

Does someone have an idea why this could be happening?

1
after redirection, the user is still anonymous but authenticated ?mlwacosmos
Yeah the user is authenticated anonymously (anon.) after redirect. Debug bar also says session is started. The session id however does not change.user3090586
I've found out if I add a return; at the first line of this method the login works fine: Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage:regenerate(); I think something goes tits up when session_regenerate_id() is called. I'll try to have a look into the why later tonight.user3090586
Any luck? I have the same issue.greg
I'm having a similar issue, but its when switching users, instead of pages.JonnyS

1 Answers

-6
votes

Set the context variable in security.yml for your firewall(s).

That should do the trick ...