Search code examples
symfonysymfony-security

Custom Authentication doesn't authenticate the user correctly


I am setting my own custom authenticator in symfony 2.6 however I have got an issue. It doesn't authenticate my user correctly. It does authenticate successfully at first then it fails.

Here goes my security.yml

security:
    encoders:
        MLM\Bundle\MLMBundle\Entity\Empreendedor:
            algorithm: bcrypt
            cost: 12

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_EMPREENDEDOR:        ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    providers:
        empreendedor_provider:
            id: empreendedor.user.provider


    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

        area_empreendedor_login:
            pattern:  ^/escritorio-virtual/login$
            #anonymous: ~
            security: false
        area_empreendedor:
            pattern: ^/escritorio-virtual
            provider: empreendedor_provider
            simple_form:
                authenticator: empreendedor_authenticator
                check_path: escritorio_virtual_login_check
                login_path: escritorio_virtual_login
            logout:
                path:   escritorio_virtual_logout
                target: escritorio_virtual_index

    # with these settings you can restrict or allow access for different parts
    # of your application based on roles, ip, host or methods
    # http://symfony.com/doc/current/cookbook/security/access_control.html
    access_control:
        - { path: ^/escritorio-virtual, roles: ROLE_EMPREENDEDOR }

my custom authenticator

class EmpreendedorAuthenticator implements SimpleFormAuthenticatorInterface
{
    private $encoder;

    public function __construct(UserPasswordEncoderInterface $encoder)
    {
        $this->encoder = $encoder;
    }

    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        try {
            $user = $userProvider->loadUserByUsername($token->getUsername());
        } catch (UsernameNotFoundException $e) {
            throw new AuthenticationException('Invalid username or password. 1');
        }

        $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials());

        if ($passwordValid) {

            return new UsernamePasswordToken(
                $user,
                $user->getPassword(),
                $providerKey,
                $user->getRoles()
            );
        }

        throw new AuthenticationException('Invalid username or password. 2');
    }

    public function supportsToken(TokenInterface $token, $providerKey)
    {
        return $token instanceof UsernamePasswordToken
        && $token->getProviderKey() === $providerKey;

    }

    public function createToken(Request $request, $username, $password, $providerKey)
    {
        return new UsernamePasswordToken($username, $password, $providerKey);
    }
}

And my log

[2015-06-02 14:46:33] request.INFO: Matched route "escritorio_virtual_login_check" (parameters: "_controller": "MLM\Bundle\MLMBundle\Controller\EscritorioVirtualSecurityController::loginCheckAction", "_route": "escritorio_virtual_login_check") [] []
[2015-06-02 14:46:33] security.DEBUG: Read SecurityContext from the session [] []
[2015-06-02 14:46:33] security.DEBUG: Reloading user from user provider. [] []
[2015-06-02 14:46:33] doctrine.DEBUG: SELECT t0.id AS id1, t0.nome AS nome2, t0.codigo_indicacao AS codigo_indicacao3, t0.rua AS rua4, t0.numero AS numero5, t0.complemento AS complemento6, t0.bairro AS bairro7, t0.cidade AS cidade8, t0.cep AS cep9, t0.cpf AS cpf10, t0.email AS email11, t0.username AS username12, t0.telefone_fixo AS telefone_fixo13, t0.telefone_celular AS telefone_celular14, t0.telefone_comercial AS telefone_comercial15, t0.password AS password16, t0.is_active AS is_active17, t0.lft AS lft18, t0.rgt AS rgt19, t0.criado AS criado20, t0.atualizado AS atualizado21, t0.is_enabled AS is_enabled22, t0.is_account_non_locked AS is_account_non_locked23, t0.is_account_non_expired AS is_account_non_expired24, t0.email_confirmado AS email_confirmado25, t0.email_confirmado_em AS email_confirmado_em26, t0.aprovado AS aprovado27, t0.aprovado_em AS aprovado_em28, t0.aprovado_por AS aprovado_por29, t0.foto AS foto30, t0.estado_id AS estado_id31, t0.patrocinador_id AS patrocinador_id32 FROM empreendedor t0 WHERE t0.email = ? LIMIT 1 ["[email protected]"] []
[2015-06-02 14:46:33] security.DEBUG: Username "[email protected]" was reloaded from user provider. [] []
[2015-06-02 14:46:33] doctrine.DEBUG: SELECT t0.id AS id1, t0.nome AS nome2, t0.codigo_indicacao AS codigo_indicacao3, t0.rua AS rua4, t0.numero AS numero5, t0.complemento AS complemento6, t0.bairro AS bairro7, t0.cidade AS cidade8, t0.cep AS cep9, t0.cpf AS cpf10, t0.email AS email11, t0.username AS username12, t0.telefone_fixo AS telefone_fixo13, t0.telefone_celular AS telefone_celular14, t0.telefone_comercial AS telefone_comercial15, t0.password AS password16, t0.is_active AS is_active17, t0.lft AS lft18, t0.rgt AS rgt19, t0.criado AS criado20, t0.atualizado AS atualizado21, t0.is_enabled AS is_enabled22, t0.is_account_non_locked AS is_account_non_locked23, t0.is_account_non_expired AS is_account_non_expired24, t0.email_confirmado AS email_confirmado25, t0.email_confirmado_em AS email_confirmado_em26, t0.aprovado AS aprovado27, t0.aprovado_em AS aprovado_em28, t0.aprovado_por AS aprovado_por29, t0.foto AS foto30, t0.estado_id AS estado_id31, t0.patrocinador_id AS patrocinador_id32 FROM empreendedor t0 WHERE t0.email = ? LIMIT 1 ["[email protected]"] []
[2015-06-02 14:46:34] security.INFO: User "[email protected]" has been authenticated successfully [] []
[2015-06-02 14:46:34] security.DEBUG: Fallback to the default authentication success handler [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DumpListener::configure". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\TranslatorListener::onKernelRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Listener "Symfony\Component\Security\Http\Firewall::onKernelRequest" stopped propagation of the event "kernel.request". [] []
[2015-06-02 14:46:34] event.DEBUG: Listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest" was not called for event "kernel.request". [] []
[2015-06-02 14:46:34] event.DEBUG: Listener "Knp\Bundle\PaginatorBundle\Subscriber\SlidingPaginationSubscriber::onKernelRequest" was not called for event "kernel.request". [] []
[2015-06-02 14:46:34] event.DEBUG: Listener "Stof\DoctrineExtensionsBundle\EventListener\BlameListener::onKernelRequest" was not called for event "kernel.request". [] []
[2015-06-02 14:46:34] security.DEBUG: Write SecurityContext in the session [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener::onKernelResponse". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\SaveSessionListener::onKernelResponse". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelFinishRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\TranslatorListener::onKernelFinishRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelFinishRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\Security\Http\Firewall::onKernelFinishRequest". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener::onTerminate". [] []
[2015-06-02 14:46:34] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelTerminate". [] []
[2015-06-02 14:46:34] request.INFO: Matched route "escritorio_virtual_index" (parameters: "_controller": "Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction", "path": "/escritorio-virtual/", "permanent": "true", "scheme": "null", "httpPort": "80", "httpsPort": "443", "_route": "escritorio_virtual_index") [] []
[2015-06-02 14:46:34] security.DEBUG: Read SecurityContext from the session [] []
[2015-06-02 14:46:34] security.DEBUG: Reloading user from user provider. [] []
[2015-06-02 14:46:34] doctrine.DEBUG: SELECT t0.id AS id1, t0.nome AS nome2, t0.codigo_indicacao AS codigo_indicacao3, t0.rua AS rua4, t0.numero AS numero5, t0.complemento AS complemento6, t0.bairro AS bairro7, t0.cidade AS cidade8, t0.cep AS cep9, t0.cpf AS cpf10, t0.email AS email11, t0.username AS username12, t0.telefone_fixo AS telefone_fixo13, t0.telefone_celular AS telefone_celular14, t0.telefone_comercial AS telefone_comercial15, t0.password AS password16, t0.is_active AS is_active17, t0.lft AS lft18, t0.rgt AS rgt19, t0.criado AS criado20, t0.atualizado AS atualizado21, t0.is_enabled AS is_enabled22, t0.is_account_non_locked AS is_account_non_locked23, t0.is_account_non_expired AS is_account_non_expired24, t0.email_confirmado AS email_confirmado25, t0.email_confirmado_em AS email_confirmado_em26, t0.aprovado AS aprovado27, t0.aprovado_em AS aprovado_em28, t0.aprovado_por AS aprovado_por29, t0.foto AS foto30, t0.estado_id AS estado_id31, t0.patrocinador_id AS patrocinador_id32 FROM empreendedor t0 WHERE t0.email = ? LIMIT 1 ["[email protected]"] []
[2015-06-02 14:46:34] security.DEBUG: Username "[email protected]" was reloaded from user provider. [] []
[2015-06-02 14:46:34] doctrine.DEBUG: SELECT t0.id AS id1, t0.nome AS nome2, t0.codigo_indicacao AS codigo_indicacao3, t0.rua AS rua4, t0.numero AS numero5, t0.complemento AS complemento6, t0.bairro AS bairro7, t0.cidade AS cidade8, t0.cep AS cep9, t0.cpf AS cpf10, t0.email AS email11, t0.username AS username12, t0.telefone_fixo AS telefone_fixo13, t0.telefone_celular AS telefone_celular14, t0.telefone_comercial AS telefone_comercial15, t0.password AS password16, t0.is_active AS is_active17, t0.lft AS lft18, t0.rgt AS rgt19, t0.criado AS criado20, t0.atualizado AS atualizado21, t0.is_enabled AS is_enabled22, t0.is_account_non_locked AS is_account_non_locked23, t0.is_account_non_expired AS is_account_non_expired24, t0.email_confirmado AS email_confirmado25, t0.email_confirmado_em AS email_confirmado_em26, t0.aprovado AS aprovado27, t0.aprovado_em AS aprovado_em28, t0.aprovado_por AS aprovado_por29, t0.foto AS foto30, t0.estado_id AS estado_id31, t0.patrocinador_id AS patrocinador_id32 FROM empreendedor t0 WHERE t0.email = ? LIMIT 1 ["[email protected]"] []
[2015-06-02 14:46:34] security.INFO: Authentication exception occurred; redirecting to authentication entry point (Invalid username or password. 2) [] []
[2015-06-02 14:46:34] security.DEBUG: Calling Authentication entry point [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException". [] []
[2015-06-02 14:46:35] event.DEBUG: Listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException" stopped propagation of the event "kernel.exception". [] []
[2015-06-02 14:46:35] event.DEBUG: Listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException" was not called for event "kernel.exception". [] []
[2015-06-02 14:46:35] event.DEBUG: Listener "Symfony\Component\HttpKernel\EventListener\ExceptionListener::onKernelException" was not called for event "kernel.exception". [] []
[2015-06-02 14:46:35] security.DEBUG: Write SecurityContext in the session [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener::onKernelResponse". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\SaveSessionListener::onKernelResponse". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelFinishRequest". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\TranslatorListener::onKernelFinishRequest". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelFinishRequest". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.finish_request" to listener "Symfony\Component\Security\Http\Firewall::onKernelFinishRequest". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener::onTerminate". [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelTerminate". [] []
[2015-06-02 14:46:35] request.INFO: Matched route "escritorio_virtual_login" (parameters: "_controller": "MLM\Bundle\MLMBundle\Controller\EscritorioVirtualSecurityController::loginAction", "_route": "escritorio_virtual_login") [] []
[2015-06-02 14:46:35] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure". [] []

Solution

  • I sorted out the issue. I missed one field in user serialization which was the username. That's why after a redirect, the authentication fails. The username couldn't be recovered. After adding it. It works like a charm.

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->name,
            $this->username,
            $this->email,
            $this->password,
            $this->isEnabled,
            $this->isAccountNonExpired,
            $this->isAccountNonLocked,
        ));
    }
    
    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->name,
            $this->username,
            $this->email,
            $this->password,
            $this->isEnabled,
            $this->isAccountNonExpired,
            $this->isAccountNonLocked,
            ) = unserialize($serialized);
    }